Check if a number is divisible by 31 or not
Last Updated :
24 Nov, 2021
Given a number N, the task is to check whether the number is divisible by 31 or not.
Examples:
Input: N = 1922
Output: Yes
Explanation:
31 * 62 = 1922
Input: N = 2722400
Output: No
Approach: The divisibility test of 31 is:
- Extract the last digit.
- Subtract 3 * last digit from the remaining number obtained after removing the last digit.
- Repeat the above steps until a two-digit number, or zero, is obtained.
- If the two-digit number is divisible by 31, or it is 0, then the original number is also divisible by 31.
For example:
If N = 49507
Step 1:
N = 49507
Last digit = 7
Remaining number = 4950
Subtracting 3 times last digit
Resultant number = 4950 - 3*7 = 4929
Step 2:
N = 4929
Last digit = 9
Remaining number = 492
Subtracting 3 times last digit
Resultant number = 492 - 3*9 = 465
Step 3:
N = 465
Last digit = 5
Remaining number = 46
Subtracting 3 times last digit
Resultant number = 46 - 3*5 = 31
Step 4:
N = 31
Since N is a two-digit number,
and 31 is divisible by 31
Therefore N = 49507 is also divisible by 31
Below is the implementation of the above approach:
C++
#include<bits/stdc++.h>
#include<stdlib.h>
using namespace std;
bool isDivisible( int n)
{
int d;
while (n / 100)
{
d = n % 10;
n /= 10;
n = abs (n-(d * 3));
}
return (n % 31 == 0) ;
}
int main()
{
int N = 1922;
if (isDivisible(N))
cout<< "Yes" <<endl ;
else
cout<< "No" <<endl ;
return 0;
}
|
Java
import java.util.*;
class GFG{
static boolean isDivisible( int n)
{
int d;
while ((n / 100 ) > 0 )
{
d = n % 10 ;
n /= 10 ;
n = Math.abs(n - (d * 3 ));
}
return (n % 31 == 0 ) ;
}
public static void main(String[] args)
{
int N = 1922 ;
if (isDivisible(N))
System.out.print( "Yes" );
else
System.out.print( "No" );
}
}
|
Python 3
def isDivisible(n) :
while n / / 100 :
d = n % 10
n / / = 10
n = abs (n - (d * 3 ))
return (n % 31 = = 0 )
if __name__ = = "__main__" :
n = 1922
if (isDivisible(n)) :
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
class GFG{
static bool isDivisible( int n)
{
int d;
while ((n / 100) > 0)
{
d = n % 10;
n /= 10;
n = Math.Abs(n - (d * 3));
}
return (n % 31 == 0) ;
}
public static void Main(String[] args)
{
int N = 1922;
if (isDivisible(N))
Console.Write( "Yes" );
else
Console.Write( "No" );
}
}
|
Javascript
<script>
function isDivisible(n)
{
let d;
while (Math.floor(n / 100) > 0)
{
d = n % 10;
n = Math.floor(n / 10);
n = Math.abs(n - (d * 3));
}
return (n % 31 == 0) ;
}
let N = 1922;
if (isDivisible(N) != 0)
document.write( "Yes" ) ;
else
document.write( "No" );
</script>
|
Time Complexity: O(log10N)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...