A number is a Repunit in base B if it can be represented as a string of three or more 1’s in a base >= 2.
Check if N is a Repunit number
Given an integer N, the task is to check if N is a Repunit number in base B.
Examples:
Input: N = 31, B = 5
Output: Yes
31 can be written as 111 base in 5
Input: N = 5, B = 2
Output: No
5 is 101 in base 2
Approach: We will count the number of one’s in the base B of a given number N and also count the number of digits in the base B of a given number N. If they are same, print “YES” else print “NO”.
For Example:
N = 31, B = 5
31 can be written as 111 base in 5, So number of one’s in base B of a given number N = 3 and number of digits in the base B of a given number N = 3
Since both are equal hence 31 is a Repunit number in base 5.
Below is the implementation of the above approach:
C++
#include <iostream>
#include <math.h>
using namespace std;
bool isRepunitNum( int n, int b)
{
int length = 0;
int countOne = 0;
while (n != 0) {
int r = n % b;
length++;
if (r == 1)
countOne++;
n = n / b;
}
return countOne >= 3 && countOne == length;
}
int main()
{
int n = 31;
int base = 2;
if (isRepunitNum(n, base))
cout << "Yes" ;
else
cout << "NO" ;
return 0;
}
|
Java
class GFG{
static boolean isRepunitNum( int n, int b)
{
int length = 0 ;
int countOne = 0 ;
while (n != 0 )
{
int r = n % b;
length++;
if (r == 1 )
countOne++;
n = n / b;
}
return countOne >= 3 &&
countOne == length;
}
public static void main(String[] args)
{
int n = 31 ;
int base = 2 ;
if (isRepunitNum(n, base))
System.out.print( "Yes" );
else
System.out.print( "No" );
}
}
|
Python3
def isRepunitNum(n, b):
length = 0 ;
countOne = 0 ;
while (n ! = 0 ):
r = n % b;
length + = 1 ;
if (r = = 1 ):
countOne + = 1 ;
n = n / / b;
return countOne > = 3 and countOne = = length;
if __name__ = = '__main__' :
n = 31 ;
base = 2 ;
if (isRepunitNum(n, base)):
print ( "Yes" );
else :
print ( "No" );
|
C#
using System;
class GFG{
static bool isRepunitNum( int n, int b)
{
int length = 0;
int countOne = 0;
while (n != 0)
{
int r = n % b;
length++;
if (r == 1)
countOne++;
n = n / b;
}
return countOne >= 3 &&
countOne == length;
}
public static void Main()
{
int n = 31;
int base1 = 2;
if (isRepunitNum(n, base1))
Console.Write( "Yes" );
else
Console.Write( "No" );
}
}
|
Javascript
<script>
function isRepunitNum( n ,b) {
let length = 0;
let countOne = 0;
while (n != 0) {
let r = n % b;
length++;
if (r == 1)
countOne++;
n = parseInt(n / b);
}
return countOne >= 3 && countOne == length;
}
let n = 31;
let base = 2;
if (isRepunitNum(n, base))
document.write( "Yes" );
else
document.write( "No" );
</script>
|
Time Complexity: O(logbn)
Auxiliary Space: O(1)
Reference: http://www.numbersaplenty.com/set/repunit/
Last Updated :
16 Jul, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...