📌  相关文章
📜  检查前N个自然数的串联是否可被3整除

📅  最后修改于: 2021-04-29 11:15:45             🧑  作者: Mango

给定整数N ,任务是检查前N个自然数的串联是否被3整除。如果可分割的,则打印是;否则,则打印否”

例子

天真的方法
最简单的方法是连接前N个自然数,并计算结果数的位数之和,然后检查该数是否可被3整除。
时间复杂度: O(N)
辅助空间: O(1)
高效方法:
为了优化上述方法,我们可以观察到一种模式。第一N的自然数的级联是不被3整除以下系列1,4,7,10,13,16,19,等等。该级数的第N由公式3×n +1给出因此,如果(N – 1)不能被3整除,则结果数可以被3整除,因此打印Yes 。否则,打印编号。
下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
 
using namespace std;
 
// Function that returns True if
// concatenation of first N natural
// numbers is divisible by 3
bool isDivisible(int N)
{
    // Check using the formula
    return (N - 1) % 3 != 0;
}
 
 
// Driver Code
int main()
{
    // Given Number
    int N = 6;
     
    // Function Call
    if (isDivisible(N))
        cout << ("Yes");
     
    else
        cout << ("No");
     
    return 0;
}
 
// This code is contributed by Mohit Kumar


Java
// Java program for the above approach
class GFG{
  
// Function that returns True if
// concatenation of first N natural
// numbers is divisible by 3
static boolean isDivisible(int N)
{
    // Check using the formula
    return (N - 1) % 3 != 0;
}
  
  
// Driver Code
public static void main(String[] args)
{
    // Given Number
    int N = 6;
      
    // Function Call
    if (isDivisible(N))
        System.out.println("Yes");
      
    else
        System.out.println("No");
}
}
 
// This code is contributed by Ritik Bansal


Python 3
# Python program for the above approach
 
# Function that returns True if
# concatenation of first N natural
# numbers is divisible by 3
def isDivisible(N):
 
    # Check using the formula
    return (N - 1) % 3 != 0
 
 
# Driver Code
if __name__ == "__main__":
 
    # Given Number
    N = 6
 
    # Function Call
    if (isDivisible(N)):
        print("Yes")
 
    else:
        print("No")


C#
// C# program for the above approach
using System;
class GFG{
 
// Function that returns True if
// concatenation of first N natural
// numbers is divisible by 3
static bool isDivisible(int N)
{
    // Check using the formula
    return (N – 1) % 3 != 0;
}
 
// Driver Code
public static void Main()
{
    // Given Number
    int N = 6;
     
    // Function Call
    if (isDivisible(N))
    Console.Write("Yes");
     
    else
    Console.Write("No");
}
}
 
// This code is contributed by Code_Mech


Javascript


输出:
Yes

时间复杂度: O(1)
辅助空间: O(1)