HDU ACM1163——Eddy's digital Roots

41 篇文章 0 订阅
34 篇文章 0 订阅

Eddy’s digital Roots

Problem Description

The digital root of a positive integer is found by summing the digits of the integer. If the resulting value is a single digit then that digit is the digital root. If the resulting value contains two or more digits, those digits are summed and the process is repeated. This is continued as long as necessary to obtain a single digit.

For example, consider the positive integer 24. Adding the 2 and the 4 yields a value of 6. Since 6 is a single digit, 6 is the digital root of 24. Now consider the positive integer 39. Adding the 3 and the 9 yields 12. Since 12 is not a single digit, the process must be repeated. Adding the 1 and the 2 yeilds 3, a single digit and also the digital root of 39.

The Eddy’s easy problem is that : give you the n,want you to find the n^n’s digital Roots.

Input

The input file will contain a list of positive integers n, one per line. The end of the input will be indicated by an integer value of zero. Notice:For each integer in the input n(n<10000).

Output

Output n^n’s digital root on a separate line of the output.

Sample Input

2
4
0

Sample Output

4
4

题目大意:求N^N的数字根。
之前做过一个类似的[杭电1013](
https://blog.csdn.net/BarisGuo/article/details/82049985),不同的是杭电1013将那个数字用字符串形式给了你,而这道题却需要你自己算。死算是不可能算出来的,所以必须找规律。之后我发现将n*n不断取数字根相乘所得结果便是n^n的数字根。得此代码:

#include<stdio.h>
int f(int x){   /*计算数字根*/
    while(x>=10)
        x=x/10+x%10;
    return x;
}
int main()
{
    int n,i,root;
    while(scanf("%d",&n)!=EOF){
        if(n==0)break;
        root=f(n);   
        for(i=1;i<n;i++)     
            root=n*f(root);
        root=f(root);
        printf("%d\n",root);
    }
    return 0;
 } 

之后借鉴他人所作,才知晓此处运用了九余数定理,即一个数的树根等于该数对九的余数。如此一来,代码就更简单了:

#include<stdio.h>
int main()
{
    int n,a;
    while(scanf("%d",&n)!=EOF){
        a=1;
        for(int i=0;i<n;i++)
        a=a * n % 9;
        if(a==0) a=9; 
        printf("%d\n",a);
    }
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值