以下為關鍵程式碼:
int isHappyNumber(int n)
{
int i, len = 1, sum = 0, recode[50];
if (n == 1) return len;
while (sum != 1)
{
recode[len ++] = n;
sum = 0;
for (i = 10; (n / i) != 0 || (n % i) != 0; )
{
sum += (n % i) * (n % i);
n /= i;
}
n = sum;
for (i = 0; i < len; i ++)
if (recode[i] == sum)
return 0;
}
return len;
}
則主程式內只須這樣寫:
for (k = i; k <= j; k++)
if (isHappyNumber(k))
printf("%d %d\n", k, isHappyNumber(k));
By David.K
p944題目連結
回ACM題庫目錄
回首頁
沒有留言:
張貼留言