Open In App

Check if a large number is divisible by 13 or not

Improve
Improve
Like Article
Like
Save
Share
Report

Given a large number, the task is to check if the number is divisible by 13 or not. 

Examples : 

Input :  637
Output : 637 is divisible by 13.
Input : 920
Output : 920 is not divisible by 13.
Input : 83959092724
Output : 83959092724 is divisible by 13.

If the given number num is small, we can easily find whether it is divisible by 13 or not by doing num % 13 and checking whether the result is 0 or not. But what about very large numbers? Let’s discuss large numbers.

Below are some interesting facts about the divisibility of 13. 

  • A number is divisible by 13 if and if the alternating sum (alternatively adding and subtracting) of blocks of three from right to left is divisible by 13. For example, 2911285 is divisible by 13 because the alternating sum of blocks of size 3 is 2 – 911 + 285 = -650 which is divisible by 13.
  • A number is divisible by 13 if and only if the number obtained by adding the last digit multiplied by 4 to the rest is also divisible by 13. 
    For example, consider 2353. Applying above rule, we get 235 + 3*4 = 247. Again we apply the rule and get 24 + 7*4 = 52. Since 52 is divisible by 13, the given number is divisible by 13. 

Below is the implementation based on first fact above (Finding the alternating sum of blocks of size 3) 

C++




// CPP program to check
// whether a number is
// divisible by 13 or not.
#include <iostream>
using namespace std;
 
// Returns true if number
// is divisible by 13 else
// returns false
bool checkDivisibility(string num)
{
    int length = num.size();
    if (length == 1 && num[0] == '0')
        return true;
 
    // Append required 0s .
    // at the beginning.
    if (length % 3 == 1)
    {
        // Same as strcat(num, "00");
        // in c.
        num +="00";
        length += 2;
    }
    else if (length % 3 == 2)
    {
        // Same as strcat(num, "0");
        // in c.
        num += "0";
        length += 1;
    }
 
    // Alternatively add/subtract
    // digits in group of three
    // to result.
    int sum = 0, p = 1;
    for (int i = length - 1; i >= 0; i--)
    {
        // Store group of three
        // numbers in group variable.
        int group = 0;
        group += num[i--] - '0';
        group += (num[i--] - '0') * 10;
        group += (num[i] - '0') * 100;
 
        sum = sum + group * p;
 
        // Generate alternate series
        // of plus and minus
        p *= (-1);
    }
    sum = abs(sum);
    return (sum % 13 == 0);
}
 
// Driver code
int main()
{
    string number = "83959092724";
    if (checkDivisibility(number))
        cout << number << " is divisible by 13.";
    else
        cout << number << " is not divisible by 13.";
    return 0;
}


Java




// Java program to check
// whether a number is
// divisible by 13 or not.
 
class GFG
{
     
// Returns true if number
// is divisible by 13 else
// returns false
static boolean checkDivisibility(String num)
{
    int length = num.length();
    if (length == 1 &&
        num.charAt(0) == '0')
        return true;
 
    // Append required 0s .
    // at the beginning.
    if (length % 3 == 1)
    {
        // Same as strcat(num, "00");
        // in c.
        num +="00";
        length += 2;
    }
    else if (length % 3 == 2)
    {
        // Same as strcat(num, "0");
        // in c.
        num += "0";
        length += 1;
    }
 
    // Alternatively add/subtract
    // digits in group of three
    // to result.
    int sum = 0, p = 1;
    for (int i = length - 1; i >= 0; i--)
    {
        // Store group of three
        // numbers in group variable.
        int group = 0;
        group += num.charAt(i--) - '0';
        group += (num.charAt(i--) - '0') * 10;
        group += (num.charAt(i) - '0') * 100;
 
        sum = sum + group * p;
 
        // Generate alternate series
        // of plus and minus
        p *= (-1);
    }
    sum = Math.abs(sum);
    return (sum % 13 == 0);
}
 
// Driver code
public static void main(String[] args)
{
    String number = "83959092724";
     
    if (checkDivisibility(number))
            System.out.println(number +
                       " is divisible by 13.");
        else
            System.out.println(number +
                       " is not divisible by 13.");
}
}
 
// This code is contributed by mits


Python3




# Python 3 program to check whether a
# number is divisible by 13 or not
 
# Returns true if number is divisible
# by 13 else returns false
def checkDivisibility( num):
    length = len(num)
    if (length == 1 and num[0] == '0'):
        return True
 
    # Append required 0s at the beginning.
    if (length % 3 == 1):
         
        # Same as strcat(num, "00");
        # in c.
        num = str(num) + "00"
        length += 2
     
    elif (length % 3 == 2):
         
        # Same as strcat(num, "0");
        # in c.
        num = str(num) + "0"
        length += 1
 
    # Alternatively add/subtract digits 
    # in group of three to result.
    sum = 0
    p = 1
    for i in range(length - 1, -1 , -1) :
         
        # Store group of three
        # numbers in group variable.
        group = 0
        group += ord(num[i]) - ord('0')
        i -= 1
        group += (ord(num[i]) - ord('0')) * 10
        i -= 1
        group += (ord(num[i]) - ord('0')) * 100
 
        sum = sum + group * p
 
        # Generate alternate series
        # of plus and minus
        p *= (-1)
    sum = abs(sum)
    return (sum % 13 == 0)
 
# Driver code
if __name__ == "__main__":
    number = "83959092724"
    if (checkDivisibility(number)):
        print( number , "is divisible by 13.")
    else:
        print( number ,"is not divisible by 13.")
 
# This code is contributed by ChitraNayal


C#




// C# program to check
// whether a number is
// divisible by 13 or not.
using System;
 
class GFG {
     
    // Returns true if number
    // is divisible by 13 else
    // returns false
    static bool checkDivisibility(string num)
    {
        int length = num.Length;
        if (length == 1 && num[0] == '0')
            return true;
     
        // Append required 0s .
        // at the beginning.
        if (length % 3 == 1)
        {
            // Same as strcat(num, "00");
            // in c.
            num +="00";
            length += 2;
        }
        else if (length % 3 == 2)
        {
            // Same as strcat(num, "0");
            // in c.
            num += "0";
            length += 1;
        }
 
        // Alternatively add/subtract
        // digits in group of three
        // to result.
        int sum = 0, p = 1;
        for (int i = length - 1; i >= 0; i--)
        {
            // Store group of three
            // numbers in group variable.
            int group = 0;
            group += num[i--] - '0';
            group += (num[i--] - '0') * 10;
            group += (num[i] - '0') * 100;
     
            sum = sum + group * p;
     
            // Generate alternate series
            // of plus and minus
            p *= (-1);
        }
        sum = Math.Abs(sum);
        return (sum % 13 == 0);
    }
     
    // Driver code
    static void Main()
    {
        string number = "83959092724";
         
        if (checkDivisibility(number))
                Console.Write( number +
                    " is divisible by 13.");
            else
                Console.Write( number +
                  " is not divisible by 13.");
    }
}
 
// This code is contributed by Sam007


Javascript




<script>
// Javascript program to check
// whether a number is
// divisible by 13 or not.
 
// Returns true if number
// is divisible by 13 else
// returns false
function checkDivisibility(num)
{
    let length = num.length;
    if (length == 1 &&
        num[0] == '0')
        return true;
 
    // Append required 0s
    // at the beginning.
    if (length % 3 == 1)
    {
        // Same as strcat(num, "00");
        // in c.
        num += "00";
        length += 2;
    }
    else if (length % 3 == 2)
    {
        // Same as strcat(num, "0");
        // in c.
        num += "0";
        length += 1;
    }
 
    // Alternatively add/subtract
    // digits in group of three
    // to result.
    let sum = 0; p = 1;
    for (let i = length - 1; i >= 0; i--)
    {
        // Store group of three
        // numbers in group variable.
        group = 0;
        group += num[i--] - '0';
        group += (num[i--] - '0') * 10;
        group += (num[i] - '0') * 100;
 
        sum = sum + group * p;
 
        // Generate alternate series
        // of plus and minus
        p *= (-1);
    }
     
    sum = Math.abs(sum);
    return (sum % 13 == 0);
}
 
// Driver code
let number = "83959092724";
if (checkDivisibility(number))
    document.write(number + " is divisible by 13.");
else
    document.write(number + " is not divisible by 13.");
 
// This code is contributed by _saurabh_jaiswal.
</script>


PHP




<?php
// PHP program to check
// whether a number is
// divisible by 13 or not.
 
// Returns true if number
// is divisible by 13 else
// returns false
function checkDivisibility($num)
{
    $length = strlen($num);
    if ($length == 1 &&
        $num[0] == '0')
        return true;
 
    // Append required 0s
    // at the beginning.
    if ($length % 3 == 1)
    {
        // Same as strcat(num, "00");
        // in c.
        $num += "00";
        $length += 2;
    }
    else if ($length % 3 == 2)
    {
        // Same as strcat(num, "0");
        // in c.
        $num += "0";
        $length += 1;
    }
 
    // Alternatively add/subtract
    // digits in group of three
    // to result.
    $sum = 0; $p = 1;
    for ($i = $length - 1; $i >= 0; $i--)
    {
        // Store group of three
        // numbers in group variable.
        $group = 0;
        $group += $num[$i--] - '0';
        $group += ($num[$i--] - '0') * 10;
        $group += ($num[$i] - '0') * 100;
 
        $sum = $sum + $group * $p;
 
        // Generate alternate series 
        // of plus and minus
        $p *= (-1);
    }
     
    $sum = abs($sum);
    return ($sum % 13 == 0);
}
 
// Driver code
$number = "83959092724";
if (checkDivisibility($number))
    echo($number . " is divisible by 13.");
else
    echo($number . " is not divisible by 13.");
 
// This code is contributed by Ajit.
?>


Output

83959092724 is divisible by 13.







Time Complexity:  O(length(number))
Auxiliary Space: O(1)

Method: Checking given number is divisible by 13 or not by using the modulo division operator “%”.  

C++




#include <iostream>
using namespace std;
 
int main() {
 
     //input
    long int n = 83959092724L;
   
    // finding given number is divisible by 13  or not
    if ((n) % 13 == 0)
    {
        cout<<"Yes";
    }
    else
    {
        cout<<"No";
    }
    return 0;
}
 
// This code is contributed by laxmigangarajula03


Java




/*package whatever //do not write package name here */
 
// Java code
// To check whether the given number is divisible by 13 or not
  
import java.io.*;
import java.util.*;
   
class GFG
{
    
  public static void main(String[] args)
  {
    //input
    long n = 83959092724L;
    // finding given number is divisible by 13  or not
      
    if ((n) % 13 == 0)
    {
        System.out.println("Yes");
    }
    else
    {
        System.out.println("No");
    }
      
  }
}
 
// This code is contributed by satwik4409.


Python3




# Python code
# To check whether the given number is divisible by 13 or not
 
#input
n=83959092724
# the above input can also be given as n=input() -> taking input from user
# finding given number is divisible by 13 or not
if int(n)%13==0:
  print("Yes")
else:
  print("No")
 
  # this code is contributed by gangarajula laxmi


C#




using System;
public class GFG {
 
    static public void Main()
    {
 
        // input
        long n = 83959092724L;
       
        // finding given number is divisible by 13  or not
        if ((n) % 13 == 0) {
            Console.Write("Yes");
        }
        else {
            Console.Write("No");
        }
    }
}
 
// This code is contributed by laxmigangarajula03


Javascript




<script>
//input
    n = 83959092724;
 
    // finding given number is divisible by 13 or not
    if (n % 13 == 0)
    {
         document.write("Yes");
    }
    else
    {
        document.write("No");
    }
     
     // This code is contributed by laxmigangarajula03
    </script>


PHP




<?php
   //input
    $n = 83959092724;
      
     
    // finding given number is divisible by 13 or not
    if ($n % 13 == 0)
    {
        echo "Yes";
    }
    else
    {
        echo "No";
    }
  
// This code is contributed by satwik4409.
?>


Output

Yes







Time Complexity: O(1)
Auxiliary Space: O(1)

Method 3: 

1. Initialize an integer variable alternating_sum to 0 and a variable multiplier to -1.
2. While num is greater than 0, perform the following steps:
         a. Add multiplier * (num % 10) to alternating_sum.
         b. Multiply multiplier by -1.
         c. Divide num by 10.
3. Check if alternating_sum is divisible by 13. If it is, return true. Otherwise, return false.

C++




#include <iostream>
 
bool is_divisible_by_13(int num)
{
    int alternating_sum = 0;
    int multiplier = -1;
    while (num > 0) {
        alternating_sum += multiplier * (num % 10);
        multiplier *= -1;
        num /= 10;
    }
    // checking if divisible by 13 or not
    return alternating_sum % 13 == 0;
}
 
int main()
{
 
    if (is_divisible_by_13(12))
        std::cout << "Yes" << std::endl; // False
    else
        std::cout << "No" << std::endl;
    return 0;
}


Java




/*package whatever //do not write package name here */
 
public class Main {
 
    public static boolean isDivisibleBy13(int num)
    {
 
        int alternatingSum = 0;
 
        int multiplier = -1;
 
        while (num > 0) {
 
            alternatingSum += multiplier * (num % 10);
 
            multiplier *= -1;
 
            num /= 10;
        }
 
        // checking if divisible by 13 or not
 
        return alternatingSum % 13 == 0;
    }
 
    public static void main(String[] args)
    {
 
        if (isDivisibleBy13(12))
 
            System.out.println("Yes"); // False
 
        else
 
            System.out.println("No");
    }
}


Python3




def is_divisible_by_13(num):
    alternating_sum = 0
    multiplier = -1
    while num > 0:
        alternating_sum += multiplier * (num % 10)
        multiplier *= -1
        num //= 10
    #checking if divisible by 11 or not
    return alternating_sum % 13 == 0
 
if is_divisible_by_13(12):
    print("Yes") # No
else:
    print("No")


C#




using System;
 
class Program
{
    static bool IsDivisibleBy11(int num)
    {
        int alternating_sum = 0;
        int multiplier = -1;
        while (num > 0)
        {
            alternating_sum += multiplier * (num % 10);
            multiplier *= -1;
            num /= 10;
        }
        // checking if divisible by 11 or not
        return alternating_sum % 13 == 0;
    }
 
    static void Main(string[] args)
    {
        if (IsDivisibleBy11(12))
            Console.WriteLine("Yes"); // False
        else
            Console.WriteLine("No");
    }
}


Javascript




function isDivisibleBy13(num) {
  let alternatingSum = 0;
  let multiplier = -1;
 
  while (num > 0) {
    alternatingSum += multiplier * (num % 10);
    multiplier *= -1;
    num = Math.floor(num / 10);
  }
 
  // checking if divisible by 13 or not
  return alternatingSum % 13 === 0;
}
 
if (isDivisibleBy13(12)) {
  console.log("Yes"); // False
} else {
  console.log("No");
}


Output

No







Time Complexity: O(log10(n))
Auxiliary Space: O(1) 

Method: Using lookup table method

  1. The remainders list contains the precomputed remainders of all numbers from 0 to 12 when divided by 13. The remainders for negative numbers are obtained by subtracting them from 13.
  2. The is_divisible_by_13() function takes a number as an input.
  3. It splits the number into blocks of three digits from right to left using the modulo operator and integer division. Each block represents a number in the range [0, 999].
  4. It computes the remainders of each block using the precomputed values and updates the remainder variable accordingly. The formula used to compute the remainder of a block is (remainder * 1000 + block) % 13. This is based on the fact that 1000 % 13 is 8, which means that 10^n % 13 is 1 for all n >= 3. Therefore, we can compute the remainder of a block by multiplying the current remainder by 1000, adding the block to it, and taking the remainder when divided by 13.
  5. If the final remainder is 0, then the function returns True, indicating that the number is divisible by 13. Otherwise, it returns False.

C++




#include <iostream>
#include <vector>
using namespace std;
 
bool isDivisibleBy13(long long number) {
    vector<int> remainders = {0, 1, 2, 3, 4, 5, -1, -2, -3, -4, -5, 1, 0};
 
    // Split the number into blocks of three digits from right to left
    vector<int> blocks;
    while (number > 0) {
        blocks.push_back(number % 1000);
        number /= 1000;
    }
 
    // Compute the remainders of each block using the precomputed values
    int remainder = 0;
    for (int i = blocks.size() - 1; i >= 0; i--) {
        remainder = remainders[(remainder * 1000 + blocks[i]) % 13];
    }
 
    // If the final remainder is 0, then the number is divisible by 13
    return remainder == 0;
}
 
int main() {
    long long number = 83959092724;
    if (isDivisibleBy13(number)) {
        cout << number << " is divisible by 13." << endl;
    } else {
        cout << number << " is not divisible by 13." << endl;
    }
    return 0;
}


Java




import java.util.ArrayList;
 
public class GFG {
 
    public static boolean isDivisibleBy13(long number) {
        // Create a list to store the remainders for each block
        int[] remainders = {0, 1, 2, 3, 4, 5, -1, -2, -3, -4, -5, 1, 0};
 
        // Split the number into blocks of three digits from right to left
        ArrayList<Integer> blocks = new ArrayList<>();
        while (number > 0) {
            blocks.add((int)(number % 1000));
            number /= 1000;
        }
 
        // Compute the remainders of each block using the precomputed values
        int remainder = 0;
        for (int i = blocks.size() - 1; i >= 0; i--) {
            remainder = remainders[(remainder * 1000 + blocks.get(i)) % 13];
        }
 
        // If the final remainder is 0, then the number is divisible by 13
        return remainder == 0;
    }
 
    public static void main(String[] args) {
        long number = 83959092724L;
        if (isDivisibleBy13(number)) {
            System.out.println(number + " is divisible by 13.");
        } else {
            System.out.println(number + " is not divisible by 13.");
        }
    }
}


Python3




# Precompute the remainders of all numbers from 0 to 12 when divided by 13
remainders = [0, 1, 2, 3, 4, 5, -1, -2, -3, -4, -5, 1, 0]
 
def is_divisible_by_13(number):
    # Split the number into blocks of three digits from right to left
    blocks = []
    while number > 0:
        blocks.append(number % 1000)
        number //= 1000
 
    # Compute the remainders of each block using the precomputed
    # values
    remainder = 0
    for block in blocks:
        remainder = remainders[(remainder * 1000 + block) % 13]
 
    # If the final remainder is 0, then the number is divisible by 13
    return remainder == 0
 
number = 83959092724
if (is_divisible_by_13(number)):
    print( number , "is divisible by 13.")
else:
    print( number ,"is not divisible by 13.")


C#




using System;
using System.Collections.Generic;
 
class GFG
{
    static bool IsDivisibleBy13(long number)
    {
        List<int> remainders = new List<int> { 0, 1, 2, 3, 4, 5, -1, -2, -3, -4, -5, 1, 0 };
 
        // Split the number into blocks of three digits from right to left
        List<int> blocks = new List<int>();
        while (number > 0)
        {
            blocks.Add((int)(number % 1000));
            number /= 1000;
        }
 
        // Compute the remainders of each block using the precomputed values
        int remainder = 0;
        for (int i = blocks.Count - 1; i >= 0; i--)
        {
            remainder = remainders[(remainder * 1000 + blocks[i]) % 13];
        }
 
        // If the final remainder is 0, then the number is divisible by 13
        return remainder == 0;
    }
 
    static void Main(string[] args)
    {
        long number = 83959092724;
        if (IsDivisibleBy13(number))
        {
            Console.WriteLine(number + " is divisible by 13.");
        }
        else
        {
            Console.WriteLine(number + " is not divisible by 13.");
        }
    }
}


Javascript




function isDivisibleBy13(number) {
  const remainders = [0, 1, 2, 3, 4, 5, -1, -2, -3, -4, -5, 1, 0];
 
  // Split the number into blocks of three digits from right to left
  const blocks = [];
  while (number > 0) {
    blocks.push(number % 1000);
    number = Math.floor(number / 1000);
  }
 
  // Compute the remainders of each block using the precomputed values
  let remainder = 0;
  for (let i = blocks.length - 1; i >= 0; i--) {
    remainder = remainders[(remainder * 1000 + blocks[i]) % 13];
  }
 
  // If the final remainder is 0, then the number is divisible by 13
  return remainder === 0;
}
 
const number = 83959092724;
if (isDivisibleBy13(number)) {
  console.log(number + " is divisible by 13.");
} else {
  console.log(number + " is not divisible by 13.");
}


Output

83959092724 is divisible by 13.







Time complexity:
The time complexity of the is_divisible_by_13() function depends on the number of blocks in the input number. The number of blocks is at most ceil(log10(number)/3), which is O(log(number)). The precomputation of the remainders takes constant time. The computation of each block’s remainder takes constant time. Therefore, the overall time complexity is O(log(number)).

Auxiliary space:
The space complexity of the is_divisible_by_13() function is O(1), as it uses only a constant amount of extra space to store the remainders of all numbers from 0 to 12. The number of blocks is at most ceil(log10(number)/3), which is also O(1) in terms of space complexity.



Last Updated : 21 Sep, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads