九余数定理(hdu-P1163)

来源:互联网 发布:项目开发报价软件 编辑:程序博客网 时间:2024/05/22 00:19

九余数定理:

一个数对九取余后的结果称为九余数。

一个数的每一位数字之和相加后得到的<10的数字称为这个数的九余数(如果相加结果大于9,则继续每一位相加)


九余数两个基本定律:

1.和的模 等于 模的和再取模 如:(15+7)%9 = (15%9+7%9)%9 逆运算也成立

2.积的模 等于 模的积再取模 如:(15*7)%9 = (15%9 * 7%9) %9 逆运算也成立


题目大意:

give you the n,want you to find the n^n's digital Roots.

给你一个n,找出n^n所对应的数字根(即基部)——即最后的结果不能超过9

数字根举例:

12:  12→1+2→3(数字根)

39:  39→3+9→12→1+2→3(数字根)


思路:

根据九余数第二条定律:n^n的九余数 = n^n%9 =( (n%9) * (n%9) * (n%9)...... )%9

再对内部进行同样的方法,是的计算所得的值减小,不会超过9;


源代码:

package acm;import java.util.Scanner;class P1163 {public static void main(String[] args) {Scanner sc = new Scanner(System.in);while(sc.hasNext()){int n = sc.nextInt();if(n==0){break;}int result = mi(n);System.out.println(result);}}//计算n次幂private static int mi(int n) {int result = 1;for(int i=0;i<n;i++){result = ( result * (n%9) )%9;//每次相乘之后再取余if(result==0){//当碰到比如3、以及9的倍数时,直接返回9return 9;}}return result;}}

1 0