| |||||
While skimming his phone directory in 1982, mathematician Albert Wilansky noticed that the telephone number of his brother-in-law H. Smith had the following peculiar property: The sum of the digits of that number was equal to the sum of the digits of the prime factors of that number. Got it? Smith's telephone number was 493-7775. This number can be written as the product of its prime factors in the following way:
As this property is true for every prime number, Wilansky excluded them from the definition. Other Smith numbers include 6,036 and 9,985.
Wilansky was not able to find a Smith number which was larger than the telephone number of his brother-in-law. Can you help him out?
Input
The input consists of several test cases, the number of which you are given in the first line of the input. Each test case consists of one line containing a single positive integer smaller than 109.Output
For every input value n, compute the smallest Smith number which is larger than n and print it on a single line. You can assume that such a number exists.Sample Input
1 4937774
Sample Output
4937775
此题大部分的OJ里都有,我在POJ,JOJ中都做过。
总觉得这么暴力解决TLE 但是终究没有。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <string>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
bool prime(int n)
{
int i;
for(i=2;i*i<=n;i++)
if(n%i==0)
return false;
return true;
}
int getsum(int x)
{
int sum=0;
while(x)
{
sum=sum+x%10;
x=x/10;
}
return sum;
}
bool judge(int x)
{
int sum1,sum2=0,i,num=0;
int p[10000];
sum1=getsum(x);
for(i=2;i*i<=x;i++)
{
if(x%i==0)
{
p[num++]=i;
x=x/i;
while(x%i==0)
{
p[num++]=i;
x=x/i;
}
}
if(x==1)
break;
}
if(x>1)
{
p[num++]=x;
}
for(i=0;i<num;i++)
{
sum2=sum2+getsum(p[i]);
}
if(sum1==sum2)
return true;
else
return false;
}
int main()
{
int n,i,cases;
cin>>cases;
while(cases--)
{
cin>>n;
for(i=n+1;;i++)
{
if(prime(i))
continue;
if(judge(i))
{
cout<<i<<endl;
break;
}
}
}
return 0;
}