# Mathematically beautiful numbers | Hackerearth practice problem solution

Problem:-

While playing a mental math game, you realize that the number k is mathematically beautiful.

You then realize that the number x can be mathematically beautiful if it is represented as a sum of a sequence where each element is a power of k and all the numbers in the sequence are different.

Input format

• The first line contains denoting the number of test cases.
• The next T lines contain $x$  and  $k$  denoting the numbers.

Output Format

For each test case, output  "YES"  if $x$ is "mathematically beautiful" and  "NO"  otherwise.

Constraints

$T<=1000$

$\left(1<=x<={10}^{18}\right)$

$\left(2<=k<=9\right)$

Sample Input
2
91 3
17 5

Sample Output
YES
NO

Time Limit: 2
Memory Limit: 256
Source Limit:
Explanation

$91={3}^{0}+{3}^{2}+{3}^{4}$

.....................................................

Code:-

Here I am going to give you two solution first one is on the basis of C language and second one is on the basis of c++ language which you can submit in c++14 and c++17 also

Solution 1 ( C language):-

#include <stdio.h>
int main()
{
int T, k, flag, i, rem;
long long int x;
scanf("%d", &T);
for(i=0; i<T; i++)
{
scanf("%lld %d",&x , &k );
flag = 0;
while(x)
{
rem = x % k ;
if(rem != 0 && rem != 1)
{
flag = 1;
break;
}
x = x/k ;
}
if(flag == 1)
printf("NO\n");
else
printf("YES\n");
}
}

Solution 2 ( C++ language):-

This solution is based on the c++ language and you can submit ib c++14 and c++17 also.
#include <iostream>
using namespace std;
int main()
{
int t,k;
long long int x;
cin>>t;
while(t--)
{
cin>>x>>k;
while(x!=0)
{
if(x%k!=0)
{
x--;
if(x%k!=0)
{
cout<<"NO"<<endl;
break;
}
else
x=x/k;
}
else
x=x/k;
if(x==0)
cout<<"YES"<<endl;
}
}
return 0;
}

Recommended Post:-

• Hackerearth Problems:-

Data structure:-
Key points:-