| Time Limit: 1000MS | Memory Limit: 10000K | |
| Total Submissions: 10627 | Accepted: 3723 |
Description
The sum of all digits of the telephone number is 4+9+3+7+7+7+5= 42,and the sum of the digits of its prime factors is equally 3+5+5+6+5+8+3+7=42. Wilansky was so amazed by his discovery that he named this kind of numbers after his brother-in-law: Smith numbers.
As this observation is also true for every prime number, Wilansky decided later that a (simple and unsophisticated) prime number is not worth being a Smith number, so he excluded them from the definition.
Wilansky published an article about Smith numbers in the Two Year College Mathematics Journal and was able to present a whole collection of different Smith numbers: For example, 9985 is a Smith number and so is 6036. However,Wilansky was not able to find a Smith number that was larger than the telephone number of his brother-in-law. It is your task to find Smith numbers that are larger than 4937775!
Input
Output
Sample Input
4937774 0
Sample Output
4937775
思路:
枚举大于给定n的所有合数(题目中说: a prime number is not worth being a Smith number)是否为Smith Number。
根据质因数分解定理,分解质因数时,可以这样做:
设要分解的合数为N,M为试除的质因数,初值为2;
1、如果N被M整除,则M为N的质因数,令N = N / M,M不变;
2、若不能整除,则N不变,M++;
重复上面两步,直到N是一个素数为止。
需要注意的是:
不需要判断当前M是否为素数,因为若为合数则必然不能整除。
#include <iostream>
#include <cstdio>
using namespace std;
bool IsPrime(int n)
{
int i;
for (i = 2; i*i <= n; i++)
{
if (n % i == 0)
{
return false;
}
}
return true;
}
int SumOfDigits(int n)
{
int sum = 0;
while (n != 0)
{
sum += n%10;
n /= 10;
}
return sum;
}
int SumOfPrimeFactors(int n)
{
int sum = 0;
int i = 2;
while (true) //合数是一定可以被分解质因数的,所以一直循环好了
{
if (n % i == 0)
{
sum += SumOfDigits(i);
if (IsPrime(n /= i))
{
break;
}
}
else
{
i++;
}
}
return sum += SumOfDigits(n);
}
int main(void)
{
int n;
while (scanf("%d", &n) != EOF && n != 0)
{
bool finished = false;
int i;
for (i = n+1; !finished; i++)
{
if (!IsPrime(i)) //素数不可能是Smith Number
{
if (SumOfDigits(i) == SumOfPrimeFactors(i))
{
printf("%d\n", i);
finished = true;
}
}
}
}
return 0;
}
2929



被折叠的 条评论
为什么被折叠?



