Problem 1057 ab from http://acm.fzu.edu.cn/problem.php?pid=1057

来源:互联网 发布:新热血英豪mac 编辑:程序博客网 时间:2024/05/16 01:17
 Problem 1057 ab

Accept: 818    Submit: 2644
Time Limit: 1000 mSec    Memory Limit : 32768 KB

 Problem Description

对于任意两个正整数a,b(0<=a,b<10000)计算ab各位数字的和的各位数字的和的各位数字的和的各位数字的和。

 Input

输入有多组数据,每组只有一行,包含两个正整数a,b。最后一组a=0,b=0表示输入结束,不需要处理。

 Output

对于每组输入数据,输出ab各位数字的和的各位数字的和的各位数字的和的各位数字的和。

 Sample Input

2 35 70 0

 Sample Output

85

 Source

FZUPC Warmup 2005

首先,设一个数为abc,那么(a*10^2+b*10+c)%9 = (a%9)*(10^2%9) + (b%9)*(10%9) + (c%9) = (a+b+c)%9。
就是说一个数的各个位数之和MOD 9等于这个数MOD 9,又(a*b)mod 9 = (a mod 9) *( b mod 9 )。思路就明朗了。但还有一个需要注意的地方,即结果为0的情况,其实是9。

#include<iostream>#include<cstdlib>#include<cstdio>using namespace std;int main(){    //freopen("in.txt", "r", stdin);    //freopen("out.txt", "w", stdout);    int a, b;    while(cin>>a>>b, a+b){        int res = 1;        if(a==0 || b==0){            cout<<1<<endl;            continue;        }        for(int i=1;i<=b;++i){            res *= a%9;            res %=9;        }        if(res==0)            cout<<9<<endl;        else            cout<<res<<endl;    }    //fclose(stdin);    //fclose(stdout);}



原创粉丝点击