【题解】HDU1163 Eddy‘s digital Roots

原题链接http://hdu.hustoj.com/showproblem.php?pid=1163


题目

Eddy’s digital Roots
Time Limit: 2000/1000 MS (Java/Others)
Memory Limit: 65536/32768 K (Java/Others)

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化为n^n,然后求其数根。
数根,即求一个数字各位上的数字之和,若得到的结果不为个位数则重复此过程,直到取得一个<10的数时,所得到的这个数即为原数的数根。


思路

初看到这道题目可能会觉得很简单,直接暴力模拟就行了,可是仔细看看数据范围n<10000,很容易猜到,暴力求解极有可能会超时,于是我们应该着手优化。

再仔细看看题目:
首先,n要求进行一次指数为自身的指数运算,那么要提高效率的话,很容易就能想到,应当是使用快速幂
在接着的处理是求上述运算后的结果数的数根,根据数根的定义,直接的求取方法是循环求和,直到结果为个位数,但是很显然,这样的效率不高,因此还需要别的方法进行优化,这时,数论中的一条定理就能起到作用了:九余数定理
所谓九余定理即是——“一个数的每位数字之和对9取余等于这个数直接对9取余”

结合上述的两种优化方法,其实就是快速幂取余,余数为9,那么,开始coding。


代码


import java.util.Scanner;

public class Main{
	
    public static void main(String[] args){            
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()){
        	int n = sc.nextInt();
        	if(n == 0)break;
        	int mi = n;
        	int temp = 1;
        	while(mi > 0){
        		if((mi&1) == 1)
        			temp = (temp*n)%9;
        		mi >>=1;
        		n = (n*n)%9;
        	}
        	System.out.println(temp==0?9:temp);
        }
    }
    
} 

要注意的是,不能忘了结果为0的情况,余数为零说明其数根为9,因此输出9。

猜你喜欢

转载自blog.csdn.net/Jourofant/article/details/107496417
今日推荐