Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Check divisibility by 7

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

Given a number N, the task is to check if it is divisible by 7 or not.
Note: You are not allowed to use the modulo operator, floating point arithmetic is also not allowed. 

Naive approach: A simple method is repeated subtraction. Following is another interesting method.
Divisibility by 7 can be checked by a recursive method. A number of the form 10a + b is divisible by 7 if and only if a – 2b is divisible by 7. In other words, subtract twice the last digit from the number formed by the remaining digits. Continue to do this until a small number. 

Example: the number 371: 37 – (2×1) = 37 – 2 = 35; 3 – (2 × 5) = 3 – 10 = -7; thus, since -7 is divisible by 7, 371 is divisible by 7. 
Following is the implementation of the above method 

C++




// A Program to check whether a number is divisible by 7
#include <bits/stdc++.h>
using namespace std;
 
int isDivisibleBy7( int num )
{
    // If number is negative, make it positive
    if( num < 0 )
        return isDivisibleBy7( -num );
 
    // Base cases
    if( num == 0 || num == 7 )
        return 1;
    if( num < 10 )
        return 0;
 
    // Recur for ( num / 10 - 2 * num % 10 )
    return isDivisibleBy7( num / 10 - 2 *
            ( num - num / 10 * 10 ) );
}
 
// Driver code
int main()
{
    int num = 616;
    if( isDivisibleBy7(num ) )
        cout << "Divisible" ;
    else
        cout << "Not Divisible" ;
    return 0;
}
 
// This code is contributed by rathbhupendra

C




// A Program to check whether a number is divisible by 7
#include <stdio.h>
 
int isDivisibleBy7( int num )
{
    // If number is negative, make it positive
    if( num < 0 )
        return isDivisibleBy7( -num );
 
    // Base cases
    if( num == 0 || num == 7 )
        return 1;
    if( num < 10 )
        return 0;
 
    // Recur for ( num / 10 - 2 * num % 10 )
    return isDivisibleBy7( num / 10 - 2 * ( num - num / 10 * 10 ) );
}
 
// Driver program to test above function
int main()
{
    int num = 616;
    if( isDivisibleBy7(num ) )
        printf( "Divisible" );
    else
        printf( "Not Divisible" );
    return 0;
}

Java




// Java program to check whether a number is divisible by 7
import java.io.*;
 
class GFG
{
    // Function to check whether a number is divisible by 7
    static boolean isDivisibleBy7(int num)
    {
        // If number is negative, make it positive
        if( num < 0 )
            return isDivisibleBy7( -num );
  
        // Base cases
        if( num == 0 || num == 7 )
            return true;
        if( num < 10 )
            return false;
  
        // Recur for ( num / 10 - 2 * num % 10 )
        return isDivisibleBy7( num / 10 - 2 * ( num - num / 10 * 10 ) );
    }
     
    // Driver program
    public static void main (String[] args)
    {
        int num = 616;
        if(isDivisibleBy7(num))
            System.out.println("Divisible");
        else
            System.out.println("Not Divisible");
    }
}
 
// Contributed by Pramod Kumar

Python3




# Python program to check whether a number is divisible by 7
 
# Function to check whether a number is divisible by 7
def isDivisibleBy7(num) :
     
    # If number is negative, make it positive
    if num < 0 :
        return isDivisibleBy7( -num )
 
    # Base cases
    if( num == 0 or num == 7 ) :
        return True
     
    if( num < 10 ) :
        return False
         
    # Recur for ( num / 10 - 2 * num % 10 )
    return isDivisibleBy7( num // 10 - 2 * ( num - num // 10 * 10 ) )
     
# Driver program
num = 616
if(isDivisibleBy7(num)) :
    print ("Divisible")
else :
    print ("Not Divisible")
 
# This code is contributed by Nikita Tiwari

C#




// C# program to check whether a
// number is divisible by 7
using System;
 
class GFG {
     
    // Function to check whether a
    // number is divisible by 7
    static bool isDivisibleBy7(int num)
    {
         
        // If number is negative,
        // make it positive
        if( num < 0 )
            return isDivisibleBy7(-num);
 
        // Base cases
        if( num == 0 || num == 7 )
            return true;
        if( num < 10 )
            return false;
 
        // Recur for ( num / 10 - 2 * num % 10 )
        return isDivisibleBy7(num / 10 - 2 *
                             ( num - num / 10 * 10 ));
    }
     
    // Driver Code
    public static void Main ()
    {
        int num = 616;
        if(isDivisibleBy7(num))
            Console.Write("Divisible");
        else
            Console.Write("Not Divisible");
    }
}
 
// This code is contributed by Nitin Mittal.

PHP




<?php
// PHP Program to check whether
// a number is divisible by 7
 
// Function to check whether a
// number is divisible by 7
function isDivisibleBy7( $num )
{
     
    // If number is negative,
    // make it positive
    if( $num < 0 )
        return isDivisibleBy7( -$num );
 
    // Base cases
    if( $num == 0 || $num == 7 )
        return 1;
    if( $num < 10 )
        return 0;
 
    // Recur for ( num / 10 - 2 * num % 10 )
    return isDivisibleBy7($num / 10 - 2 *
                         ($num - $num / 10 * 10 ) );
}
 
    // Driver Code
    $num = 616;
    if( isDivisibleBy7($num )>=0 )
        echo("Divisible");
    else
        echo("Not Divisible");
     
// This code is contributed by vt_m.
?>

Javascript




<script>
 
// js Program to check whether
// a number is divisible by 7
 
// Function to check whether a
// number is divisible by 7
function isDivisibleBy7( num )
{
     
    // If number is negative,
    // make it positive
    if( num < 0 )
        return isDivisibleBy7( -num );
 
    // Base cases
    if( num == 0 || num == 7 )
        return 1;
    if( num < 10 )
        return 0;
 
    // Recur for ( num / 10 - 2 * num % 10 )
    return isDivisibleBy7(num / 10 - 2 *
                         (num - num / 10 * 10 ) );
}
 
    // Driver Code
    let num = 616;
    if( isDivisibleBy7(num )>=0 )
        document.write("Divisible");
    else
        document.write("Not Divisible");
  
// This code is contributed by sravan kumar
 
</script>

Output

Divisible

Time Complexity: O(log n)
Auxiliary Space: O(log n)

How does this work? Let ‘b’ be the last digit of a number ‘n’ and let ‘a’ be the number we get when we split off ‘b’. 
The representation of the number may also be multiplied by any number relatively prime to the divisor without changing its divisibility. After observing that 7 divides 21, we can perform the following: 

 10.a + b 

after multiplying by 2, this becomes  

 20.a + 2.b 

and then 

 21.a - a + 2.b 

Eliminating the multiple of 21 gives 

 -a + 2b

and multiplying by -1 gives 

 a - 2b

Method: To check given number is divisible by 7 or not by using the modulo division operator “%”.  

C++




#include <bits/stdc++.h>
using namespace std;
int main()
{
 
    // To check whether the given number is divisible by
    // 7 or not
    int n = 371;
 
    // finding given number is divisible by 7 or not
    if (n % 7 == 0) {
        cout << ("divisible");
    }
    else {
        cout << ("Not divisible");
    }
}
 
// This code is contributed by garg28harsh.

Java




// Java code for the above approach
import java.io.*;
 
class GFG {
  public static void main(String[] args)
  {
 
    // To check whether the given number is divisible by
    // 7 or not
 
    int n = 371;
 
    // finding given number is divisible by 7 or not
    if ((int)n % 7 == 0) {
      System.out.print("divisible");
    }
    else {
      System.out.print("Not divisible");
    }
  }
}
 
// This code is contributed by lokesh

Python3




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

C#




// C# code for the above approach
using System;
public class GFG {
 
  static public void Main()
  {
 
    // To check whether the given number is divisible by
    // 7 or not
 
    int n = 371;
 
    // finding given number is divisible by 7 or not
    if ((int)n % 7 == 0) {
      Console.Write("divisible");
    }
    else {
      Console.Write("Not divisible");
    }
  }
}
 
// This code is contributed by lokesh

Javascript




<script>
       // JavaScript code for the above approach
 
       // To check whether the given number is divisible by 7 or not
 
       //input
       let n = 371
      
       // finding given number is divisible by 7 or not
       if (n % 7 == 0)
           document.write("divisible")
       else
           document.write("Not divisible")
 
 
 
   // This code is contributed by Potta Lokesh
   </script>

PHP




<?php
  //input
  $n=371;
 
 
// finding given number is divisible by 7 or not  
 
// checking the given number is divisible by 7 or not
if ($n % 7 == 0)
{
  echo "Divisible";
}
else
{
  echo "Not divisible";
 
// this code is contributed by gangarajula laxmi
?>

Output

divisible

Time complexity: O(1) because it is performing constant operations
Auxiliary space: O(1)

Method: Checking the divisibility using the arithmetic(/) operator

C++




#include <iostream>
using namespace std;
 
int main() {
  int n = 616;
  int quo = n/7;
  if((quo*7) == n){
    cout << "Divisible";
  }
  else{
    cout << "Not Divisible";
  }
  return 0;
}

Java




//Java code for the above approach
 
import java.io.*;
 
class Gfg {
  //Driver code
    public static void main(String[] args) {
        int n = 616;
        int quo = n/7;
        if((quo*7) == n){
            System.out.println("Divisible");
        }
        else{
            System.out.println("Not Divisible");
        }
    }
}

Python3




n = 616
quo = int(n/7)
if quo*7 == n:
  print("Divisible")
else:
  print("Not Divisible")

C#




// C# code for the above approach:
using System;
using System.Collections.Generic;
 
public class Gfg
{
 
  // Driver code
  public static void Main(string[] args)
  {
    int n = 616;
    int quo = n/7;
    if((quo*7) == n){
      Console.WriteLine("Divisible");
    }
    else{
      Console.WriteLine("Not Divisible");
    }
  }
}
 
// This code is contributed by ritaagarwal.

Javascript




let n = 616;
let quo = Math.floor(n/7);
if((quo*7) == n){
  console.log("Divisible");
}
else{
  console.log("Not Divisible");
}
 
// This code is contributed by poojaagarwal2.

Output

Divisible

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

Method: alternating digit sum

Here are the steps for the “alternating digit sum” method to check the divisibility of a number by 7:

  1. Initialize a variable multiplier to 1 and a variable result to 0.
  2. Starting from the least significant digit of the number, multiply each digit by the multiplier variable and add the result to result.
  3. If multiplier is 1, set multiplier to 2. Otherwise, set multiplier to 1.
  4. Repeat steps 2-3 until all digits have been processed.
  5. If the absolute value of result is divisible by 7, then the original number is divisible by 7. Otherwise, it is not.
     

C++




#include <iostream>
#include <cmath>
 
bool is_divisible_by_7(int num) {
    int result = 0;
    int multiplier = 1;
 
    // Iterate through the digits of the number
    while (num > 0) {
        int digit = num % 10;
        result += digit * multiplier;
 
        // Update the number and multiplier
        num /= 10;
        multiplier = 3 - multiplier; // switch between 1 and 2
    }
 
    // Check if the absolute value of result is divisible by 7
    return abs(result) % 7 == 0;
}
 
// Example usages
int main() {
    std::cout << is_divisible_by_7(434) << std::endl; // Output: 1 (True)
    std::cout << is_divisible_by_7(123456789) << std::endl; // Output: 0 (False)
    std::cout << is_divisible_by_7(-343) << std::endl; // Output: 1 (True)
    return 0;
}

Java




import java.lang.Math;
 
class Main {
    public static boolean is_divisible_by_7(int num) {
        int result = 0;
        int multiplier = 1;
 
        // Iterate through the digits of the number
        while (num > 0) {
            int digit = num % 10;
            result += digit * multiplier;
 
            // Update the number and multiplier
            num /= 10;
            multiplier = 3 - multiplier; // switch between 1 and 2
        }
 
        // Check if the absolute value of result is divisible by 7
        return Math.abs(result) % 7 == 0;
    }
 
    // Example usages
    public static void main(String[] args) {
        System.out.println(is_divisible_by_7(434)); // Output: true
        System.out.println(is_divisible_by_7(123456789)); // Output: false
        System.out.println(is_divisible_by_7(-343)); // Output: true
    }
}

Python3




def is_divisible_by_7(num):
    result = 0
    multiplier = 1
    while num > 0:
        digit = num % 10
        result += digit * multiplier
        num //= 10
        multiplier = 3 - multiplier  # switch between 1 and 2
    return abs(result) % 7 == 0
 
 
# Example usages
print(is_divisible_by_7(434))  # Output: True
print(is_divisible_by_7(123456789))  # Output: False
print(is_divisible_by_7(-343))  # Output: True

C#




using System;
 
public class MainClass {
    public static bool IsDivisibleBy7(int num)
    {
        int result = 0;
        int multiplier = 1;
        // Iterate through the digits of the number
        while (num > 0) {
            int digit = num % 10;
            result += digit * multiplier;
 
            // Update the number and multiplier
            num /= 10;
            multiplier
                = 3 - multiplier; // switch between 1 and 2
        }
 
        // Check if the absolute value of result is
        // divisible by 7
        return Math.Abs(result) % 7 == 0;
    }
 
    // Example usages
    public static void Main()
    {
        Console.WriteLine(
            IsDivisibleBy7(434)); // Output: True
        Console.WriteLine(
            IsDivisibleBy7(123456789)); // Output: False
        Console.WriteLine(
            IsDivisibleBy7(-343)); // Output: True
    }
}

Javascript




// Function to check if a number is divisible by 7
function is_divisible_by_7(num) {
    let result = 0;
    let multiplier = 1;
     
    // Iterate through the digits of the number
    while (num > 0) {
        const digit = num % 10;
        result += digit * multiplier;
     
        // Update the number and multiplier
        num = Math.floor(num / 10);
        multiplier = 3 - multiplier; // switch between 1 and 2
    }
     
    // Check if the absolute value of result is divisible by 7
    return Math.abs(result) % 7 === 0;
}
 
// Example usages
console.log(is_divisible_by_7(434)); // Output: true
console.log(is_divisible_by_7(123456789)); // Output: false
console.log(is_divisible_by_7(-343)); // Output: true

Output

True
False
True

The time complexity of the is_divisible_by_7 function is O(log n)

The auxiliary space of the function is O(1)

There are other interesting methods to check divisibility by 7 and other numbers. See the following Wiki page for details.
References: 
http://en.wikipedia.org/wiki/Divisibility_rule
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
 


My Personal Notes arrow_drop_up
Last Updated : 06 Apr, 2023
Like Article
Save Article
Similar Reads
Related Tutorials