📜  检查大数是否可以被3整除

📅  最后修改于: 2021-05-04 23:21:29             🧑  作者: Mango

给定一个数字,任务是将数字除以3。输入数字可能很大,即使我们使用long long int,也可能无法存储。
例子:

Input  : n = 769452
Output : Yes

Input  : n = 123456758933312
Output : No

Input  : n = 3635883959606670431112222
Output : Yes

由于输入数字可能很大,因此我们不能使用n%3来检查数字是否可以被3整除,尤其是在C / C++之类的语言中。这个想法是基于以下事实。

插图:

For example n = 1332
Sum of digits = 1 + 3 + 3 + 2
             = 9
Since sum is divisible by 3,
answer is Yes.

这是如何运作的?

Let us consider 1332, we can write it as
1332 = 1*1000 + 3*100 + 3*10 + 2

The proof is based on below observation:
Remainder of 10i divided by 3 is 1
So powers of 10 only result in value 1.

Remainder of "1*1000 + 3*100 + 3*10 + 2"
divided by 3 can be written as : 
1*1 + 3*1 + 3*1 + 2 = 9
The above expression is basically sum of
all digits.

Since 9 is divisible by 3, answer is yes.

下面是上述事实的实现:

C++
// C++ program to find if a number is divisible by
// 3 or not
#include
using namespace std;
 
// Function to find that number divisible by 3 or not
int check(string str)
{
    // Compute sum of digits
    int n = str.length();
    int digitSum = 0;
    for (int i=0; i


Java
// Java program to find if a number is
// divisible by 3 or not
class IsDivisible
{
    // Function to find that number
    // divisible by 3 or not
    static boolean check(String str)
    {
        // Compute sum of digits
        int n = str.length();
        int digitSum = 0;
        for (int i=0; i


Python
# Python program to find if a number is
# divisible by 3 or not
 
# Function to find that number
# divisible by 3 or not
def check(num) :
     
    # Compute sum of digits
    digitSum = 0
    while num > 0 :
        rem = num % 10
        digitSum = digitSum + rem
        num = num / 10
         
    # Check if sum of digits is
    # divisible by 3.
    return (digitSum % 3 == 0)
     
# main function
num = 1332
if(check(num)) :
    print "Yes"
else :
    print "No"
     
# This code is contributed by Nikita Tiwari.


C#
// C# program to find if a number is
// divisible by 3 or not
using System;
 
class GFG
{
    // Function to find that number
    // divisible by 3 or not
    static bool check(string str)
    {
        // Compute sum of digits
        int n = str.Length;
        int digitSum = 0;
         
        for (int i = 0; i < n; i++)
            digitSum += (str[i] - '0');
     
        // Check if sum of digits is
        // divisible by 3.
        return (digitSum % 3 == 0);
    }
 
    // main function
    public static void Main ()
    {
        string str = "1332";
         
        if(check(str))
            Console.WriteLine("Yes");
        else
            Console.WriteLine("No");
    }
}
 
// This code is contributed by vt_m.


PHP


Javascript


输出:

Yes