Given a number N, the task is to check if for every value of i (0 <= i <= len), the first i digits of a number is divisible by (len – i + 1) or not, where len is the number of digits in N. If found to be true, then print “Yes”. Otherwise, print “No”.
Examples:
Input: N = 52248.
Output: Yes
Explanation:
- 5 is divisible by 5
- 52 is divisible by 4
- 522 is divisible by 3
- 5224 is divisible by 2
- 52248 is divisible by 1
Input: N = 59268
Output : No
Approach: The idea is to traverse all the prefixes of the given number and for each prefix, check if it is satisfies the condition or not.
Follow the steps below to solve the problem:
- Initialize a variable, say i as 1, to maintain the value of (len – i + 1).
- Iterate while n is greater than 0.
- If N is not divisible by i, then return false.
- Otherwise, divide N by 10 and increase the value of i by 1.
- Finally, return true.
Below is the implementation of the above approach.
C++
#include <iostream>
using namespace std;
bool prefixDivisble( int n)
{
int i = 1;
while (n > 0) {
if (n % i != 0)
return false ;
n = n / 10;
i++;
}
return true ;
}
int main()
{
int n = 52248;
if (prefixDivisble(n))
cout << "Yes" << endl;
else
cout << "No" << endl;
return 0;
}
|
Java
import java.io.*;
class GFG{
public static boolean prefixDivisble( int n)
{
int i = 1 ;
while (n > 0 )
{
if (n % i != 0 )
return false ;
n = n / 10 ;
i++;
}
return true ;
}
public static void main (String[] args)
{
int n = 52248 ;
if (prefixDivisble(n))
System.out.println( "Yes" );
else
System.out.println( "No" );
}
}
|
Python3
def prefixDivisble(n):
i = 1
while n > 0 :
if n % i ! = 0 :
return False
n = n / / 10
i + = 1
return True
n = 52248
if (prefixDivisble(n)):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
using System.Collections.Generic;
class GFG{
static bool prefixDivisble( int n)
{
int i = 1;
while (n > 0)
{
if (n % i != 0)
return false ;
n = n / 10;
i++;
}
return true ;
}
public static void Main()
{
int n = 52248;
if (prefixDivisble(n))
Console.Write( "Yes" );
else
Console.Write( "No" );
}
}
|
Javascript
<script>
function prefixDivisble(n)
{
let i = 1;
while (n > 0)
{
if (n % i != 0)
return false ;
n = parseInt(n / 10);
i++;
}
return true ;
}
let n = 52248;
if (prefixDivisble(n) == true )
document.write( "Yes" );
else
document.write( "No" );
</script>
|
Time Complexity : O(len) where len is the number of digits in N.
Auxiliary Space : O(1)