📌  相关文章
📜  将数字分成3个部分,以使所有部分都不能被3整除

📅  最后修改于: 2021-04-26 07:14:03             🧑  作者: Mango

您会得到一个数字“ N”。您的任务是将此数字拆分为3个正整数x,y和z,以使它们的总和等于“ N”,并且这3个整数都不是3的倍数,因为N> = 2。
例子:

方法:
要将N拆分为3个数字,我们将N拆分为

  1. 如果N可以被3整除,则数字x,y,z可以分别为1、1和N-2。所有x,y和z都不能被3整除。并且(1)+(1)+(N -2)= N。
  2. 如果N不能被3整除,那么N-3也不会被3整除。因此,我们可以有x = 1,y = 2和z = N-3。此外,(1)+(2)+(N -3)= N。
C++
// CPP program to split a number into three parts such
// than none of them is divisible by 3.
#include 
using namespace std;
 
void printThreeParts(int N)
{
    // Print x = 1, y = 1 and z = N - 2
    if (N % 3 == 0)
        cout << " x = 1, y = 1, z = " << N - 2 << endl;
 
    // Otherwise, print x = 1, y = 2 and z = N - 3
    else
        cout << " x = 1, y = 2, z = " << N - 3 << endl;
}
 
// Driver code
int main()
{
    int N = 10;
    printThreeParts(N);
    return 0;
}


Java
// Java program to split a number into three parts such
// than none of them is divisible by 3.
import java.util.*;
 
class solution
{
 
static void printThreeParts(int N)
{
    // Print x = 1, y = 1 and z = N - 2
    if (N % 3 == 0)
         
        System.out.println("x = 1, y = 1, z = "+ (N-2));
 
    // Otherwise, print x = 1, y = 2 and z = N - 3
    else
        System.out.println(" x = 1, y = 2, z = "+ (N-3));
}
 
// Driver code
public static void main(String args[])
{
    int N = 10;
    printThreeParts(N);
     
}
}


Python3
# Python3 program to split a number into three parts such
# than none of them is divisible by 3.
 
def printThreeParts(N) :
 
    # Print x = 1, y = 1 and z = N - 2
    if (N % 3 == 0) :
        print(" x = 1, y = 1, z = ",N - 2)
 
    # Otherwise, print x = 1, y = 2 and z = N - 3
    else :
        print(" x = 1, y = 2, z = ",N - 3)
  
 
# Driver code
if __name__ == "__main__" :
  
    N = 10
    printThreeParts(N)
 
# This code is contributed by Ryuga


C#
// C# program to split a number into three parts such
// than none of them is divisible by 3.
using System;
 
public class GFG{
    static void printThreeParts(int N)
{
    // Print x = 1, y = 1 and z = N - 2
    if (N % 3 == 0)
        Console.WriteLine(" x = 1, y = 1, z = "+(N - 2));
 
    // Otherwise, print x = 1, y = 2 and z = N - 3
    else
        Console.WriteLine(" x = 1, y = 2, z = "+(N - 3));
}
 
// Driver code
    static public void Main (){
    int N = 10;
    printThreeParts(N);
 
 
    }
// This code is contributed by ajit.
}


PHP


Javascript


输出:
x = 1, y = 2, z = 7

时间复杂度: O(1)