The Wayback Machine - https://web.archive.org/web/20250321005210/https://www.geeksforgeeks.org/check-large-number-divisible-13-not/
Open In App

Check if a large number is divisible by 13 or not

Last Updated : 15 Feb, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

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.

[Naive Approach] – Modulo Division  

If the given number 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.

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;
}
C
#include <stdio.h>

int main() {
    //input
    long int n = 83959092724L;
    
    // finding given number is divisible by 13 or not
    if (n % 13 == 0) {
        printf("Yes");
    } else {
        printf("No");
    }
    return 0;
}
Java
public class Main {
    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");
        }
    }
}
Python
# input
n = 83959092724

# finding given number is divisible by 13 or not
if n % 13 == 0:
    print("Yes")
else:
    print("No")
C#
using System;

class Program {
    static void Main() {
        //input
        long n = 83959092724L;
        
        // finding given number is divisible by 13 or not
        if (n % 13 == 0) {
            Console.WriteLine("Yes");
        } else {
            Console.WriteLine("No");
        }
    }
}
JavaScript
// input
let n = 83959092724;

// finding given number is divisible by 13 or not
if (n % 13 === 0) {
    console.log("Yes");
} else {
    console.log("No");
}

Output
Yes

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

[Expected Approach 1] Group-Digits for Large String Input

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. 
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;

    // Make sure that the length is 
    // multiple of 3
    if (length % 3 == 1)
    {
        num +="00"; 
        length += 2;
    }
    else if (length % 3 == 2)
    {
        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;

    // Make sure that the length is 
    // multiple of 3
    if (length % 3 == 1)
    {
        num +="00"; 
        length += 2;
    }
    else if (length % 3 == 2)
    {
        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."); 
}
}
Python
# 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
    
    # Make sure that the length is 
    # multiple of 3
    if (length % 3 == 1):
        num = str(num) + "00"
        length += 2
    
    elif (length % 3 == 2):
        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.")
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;
    
        // Make sure that the length is 
        // multiple of 3
        if (length % 3 == 1)
        {
            num +="00"; 
            length += 2;
        }
        else if (length % 3 == 2)
        {
            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."); 
    }
}
JavaScript
// 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;

    // Make sure that the length is 
    // multiple of 3
    if (length % 3 == 1)
    {
        num += "00";
        length += 2;
    }
    else if (length % 3 == 2)
    {
        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))
    console.log (number + " is divisible by 13.");
else
    console.log (number + " is not divisible by 13.");
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)

[Expected Approach 2] Group-Digits and Lookup Table

We can store create a lookup table

  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. The list is, rem = {0, 1, 2, 3, 4, 5, -1, -2, -3, -4, -5, 1, 0}
  2. We split 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].
  3. 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.
  4. 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>
using namespace std;

bool isDivisibleBy13(const string &s) {
    
    // Lookup table
    int rem[] = {0, 1, 2, 3, 4, 5, -1, -2, -3, -4, -5, 1, 0};
    
    int n = s.size(), remainder = 0, power = 1;

    // Process the number in blocks of 3 digits from 
    // right to left
    for (int i = n - 1; i >= 0; i -= 3) {
        int block = 0, factor = 1;

        for (int j = i; j > i - 3 && j >= 0; --j) {
            block = (s[j] - '0') * factor + block;
            factor *= 10;
        }

        remainder = (remainder * 1000 + block) % 13;
        
        // Normalize negative remainders
        remainder = rem[(remainder + 13) % 13];  
    }
    return remainder == 0;
}

int main() {
    string num = "1300020";

    if (isDivisibleBy13(num))
        cout << "Divisible by 13\n";
    else
        cout << "Not divisible by 13\n";

    return 0;
}
Java
import java.util.*;

public class Main {
    public static boolean isDivisibleBy13(String s) {
        
        // Lookup table
        int[] rem = {0, 1, 2, 3, 4, 5, -1, -2, -3, -4, -5, 1, 0};
        int n = s.length(), remainder = 0;

        // Process the number in blocks of 3 digits 
        // from right to left
        for (int i = n - 1; i >= 0; i -= 3) {
            int block = 0, factor = 1;

            for (int j = i; j > i - 3 && j >= 0; --j) {
                block = (s.charAt(j) - '0') * factor + block;
                factor *= 10;
            }

            remainder = (remainder * 1000 + block) % 13;
            
            // Normalize negative remainders
            remainder = rem[(remainder + 13) % 13];
        }
        return remainder == 0;
    }

    public static void main(String[] args) {
        String num = "1300020";

        if (isDivisibleBy13(num))
            System.out.println("Divisible by 13");
        else
            System.out.println("Not divisible by 13");
    }
}
Python
def is_divisible_by_13(s):
    # Lookup table
    rem = [0, 1, 2, 3, 4, 5, -1, -2, -3, -4, -5, 1, 0]
    n = len(s)
    remainder = 0

    # Process the number in blocks of 3 digits 
    # from right to left
    for i in range(n - 1, -1, -3):
        block = 0
        factor = 1

        for j in range(i, max(i - 3, -1), -1):
            block = (int(s[j]) * factor) + block
            factor *= 10

        remainder = (remainder * 1000 + block) % 13
        
        # Normalize negative remainders
        remainder = rem[(remainder + 13) % 13]
    return remainder == 0

if __name__ == '__main__':
    num = "1300020"

    if is_divisible_by_13(num):
        print("Divisible by 13")
    else:
        print("Not divisible by 13")
C#
using System;

class Program {
    static bool IsDivisibleBy13(string s) {
        
        // Lookup table
        int[] rem = {0, 1, 2, 3, 4, 5, -1, -2, -3, -4, -5, 1, 0};
        int n = s.Length, remainder = 0;

        // Process the number in blocks of 3 digits 
        // from right to left
        for (int i = n - 1; i >= 0; i -= 3) {
            int block = 0, factor = 1;

            for (int j = i; j > i - 3 && j >= 0; --j) {
                block = (s[j] - '0') * factor + block;
                factor *= 10;
            }

            remainder = (remainder * 1000 + block) % 13;
            
            // Normalize negative remainders
            remainder = rem[(remainder + 13) % 13];
        }
        return remainder == 0;
    }

    static void Main() {
        string num = "1300020";

        if (IsDivisibleBy13(num))
            Console.WriteLine("Divisible by 13");
        else
            Console.WriteLine("Not divisible by 13");
    }
}
JavaScript
function isDivisibleBy13(s) {
    // Lookup table
    const rem = [0, 1, 2, 3, 4, 5, -1, -2, -3, -4, -5, 1, 0];
    let n = s.length, remainder = 0;

    // Process the number in blocks of 3 digits
    // from right to left
    for (let i = n - 1; i >= 0; i -= 3) {
        let block = 0, factor = 1;

        for (let j = i; j > i - 3 && j >= 0; --j) {
            block = (s[j] - '0') * factor + block;
            factor *= 10;
        }

        remainder = (remainder * 1000 + block) % 13;
        
        // Normalize negative remainders
        remainder = rem[(remainder + 13) % 13];
    }
    return remainder === 0;
}

const num = "1300020";

if (isDivisibleBy13(num))
    console.log("Divisible by 13");
else
    console.log("Not divisible by 13");

Output
Not divisible by 13

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



Next Article
Practice Tags :

Similar Reads

three90RightbarBannerImg