题意 :正整数24,2+4 = 6。由于6是一个单一的数字,6是24的数字根。现在考虑39。3+9=12。由于12不是一个单一的数字,该过程必须重复。1+2 = 3,一个单一的数字,也是数字根39,问题就是:给你的n,希望你找到N ^ n的数字根。
思路:就是各个位数字之和,大于10的减去10 再加上进位的1
比如 781: 7+8 = 15 > 10 15-10+1 = 6, 6 +1 = 7
减10+1等于减9,一直减9一直到不能减为止,也就是对9取余 注意当数字为9时 , 9 % 9 == 0,0 % 9 == 0要判断的
N^N对9取余,二分取模
9比较特殊,所以在每个非0的数字取余都+9,让9和0区分开,这样其他不为9的数余数就变成了两位
比如余3 再+ 9 = 12
所以在最后判断余数是否大于9 如果大于在%9
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int f(__int64 a,int n)
{
if(n == 1)
{
if(a != 0)//判断是不是0
return a % 9+9;
else
return 0;
}
else if(n % 2 == 0)
{
int t = f(a,n/2);
if(a != 0 )
return (t*t) % 9 +9;
else
return 0;
}
else
{
int t = f(a,n/2);
if(t != 0)
{
return (t*t*a) % 9+9;
}
else
return 0;
}
}
int main()
{
int n;
while(scanf("%d",&n) != EOF)
{
if(n == 0)
break;
int d = f(n,n);
if(d > 9)
d = d % 9;
printf("%d\n",d);
}
return 0;
}