hdoj1013(大数,九余数算法)

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.

 

Input

The input file will contain a list of positive integers, one per line. The end of the input will be indicated by an integer value of zero.

Output

For each integer in the input, output its digital root on a separate line of the output.

Sample Input

24 39 0

Sample Output

6 3

   第一次做直接用递归,然后wa。看了discuss后才明白。

两点:1.大数;2.九余数算法。

题目并没有说输入的数的大小,所以用int是不行的,可以用char数组来存数据。然后是九余数算法,先给出AC代码,后面介绍九余数算法:

#include<iostream>
#include<cstring>
using namespace std;

int main(){
    char s[10000];     //考虑到大数,使用char数组
    while(cin>>s&&s[0]!='0'){
        int sum=0;
        for(int i=0;i<strlen(s);i++)
            sum+=s[i]-'0';
        cout<<(sum-1)%9+1<<endl;
    }
    return 0;
}

九余数算法:

我们都知道对于十进制数,只要这个数能除尽3/9则他个位数字之和也能除尽3/9,以前只知道用没有证明过,下面来简单证明一下。

对于十进制数,举个简单的例子,这个数是abcd,他表示的大小就是 x=1000*a+100*b+10*c+d ,

我们对他进行转化 x=999*a+99*b+9*c+(a+b+c+d)

因为9一定能除尽3和9,所以对于x,只要(a+b+c+d)能除尽3和9,则x也能除尽3和9.

上面只是举了一个数,下面来针对任意进制P(P>2)证明,

假设一个n位的P进制数x是   anan-1an-2.......a3a2a1

则x=an*Pn-1+an-1*Pn-2+an-2*Pn-3+......+a3*P2+a2*P1+a1*P0.

类似于上面的操作,我们凑出来一个各位数之和,

x=(an*(Pn-1-1)+an-1*(Pn-2-1)+an-2*(Pn-3-1)+......+a3*(P2-1)+a2*(P1-1))+(a1+a2+a3+......an-2+an-1+an)

观察发现Pn-1=(Pn-1-1)*P+(P1-1)  (n>=2) 展开后发现所有的项都含有(P-1),也就是说Pn-1一定能除尽(P-1),所以也能除尽P-1的因子,所以对于任意的(P-1)得因子q,只要各位数之和(a1+a2+......+an)能除尽q,那么x也能除尽q。

        九余数算法两种用途:第一,验证:两个或多个数的加减乘除得到的结果的数根等于对应各个数的数根的加减乘除的结果的树根;第二,一个数的数根(特殊情况,如果数根为9,按0算)等于该数对9取余的结果。

   其实九余数还是很有用的,拿一道题(从网上找来的)来说吧:

   1234567891011121314……201020112012除以9,商的个位数字是多少?
   【解析】根据“弃9法”原理,判断这个多位数除以9 的余数可以直接看数字和除以9的余数,这个多位数是由1,2,3,4,5,6,……,2011,2012这些连续的自然数构成,而对于每一个自然数来说,除以9都是同余于它的各个位上数字之和,于是有:
1+2+3+….+2011+2012≡2025078≡2+2+2+5+0+7+8(mod 9),所得余数为6,这就说明123456….20112006是9的倍数,那么商的个位数字就是4。(4×9=36)

 

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值