1013:Digital Roots
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.
大意如下:数字根是一个整数且由这个整数的每一位所加起来的和构成的。如果最后的结果的值是一位数那么那个数字就是数字根。如果结果数包含两个或更多的数字,那么这些数字还要再被相加并且还要再重复这些过程。这个过程一直到只包含一个数字为止。
就是把每一位都加起来,判断它是不是一位数,如果不是那么再次把每一位相加,直到求出来的数字是一个一位数为止。
我一开始想的是用while,把每一位相加,然后直到它是一位数时再跳出循环。但是超时。并且用数组储存位数的话,它会报溢出。
所以我们又想到了用字符串来处理这些问题。
#include<stdio.h>
#include<string.h>
char ss[1000];
int main()
{
int i,j,k,s,l,t;
while(scanf("%s",ss)!=EOF) //用字符串读入 因为一开始报了溢出,所以改用
{
if(ss[0]=='0') break;
s=k=0; l=strlen(ss);
for(i=0;i<l;i++)
{
s+=ss[i]-'0';
//printf("%d\n",s);
/*while(s!=0){
k+=s%10;
s=s/10;
}*/ //这里就不用再多写一遍来求加起来的位数了 脑子短路 超时
if(s>9){ // 难道要不停地取余?
k=s;
if(s%10==0) s=k/10;
else if(s%10!=0) {
s=k%10+k/10;
}
}
}
printf("%d\n",s);
}
}
可是我这里不是很懂 为什么要不停地取余?
1014:
Uniform Generator:
就是给你一个step和一个mod数,然后让你判断那个式子seed(x+1) = [seed(x) + STEP] % MOD中是否包含了0~mod-1中所有的数
*要注意输出每一个后,都要空一行,要不然会PE。
#include<stdio.h>
#include<string.h>
int seed[100001],ss[100001];
int main(){
int step,mod;
int i,j,k;
while(scanf("%d%d",&step,&mod)!=EOF){
memset(seed,0,sizeof(seed)); memset(ss,0,sizeof(ss));
ss[0]=1;
for(i=1; ;i++){
seed[i]=(seed[i-1]+step)%mod;
ss[seed[i]]=1;
if(seed[i]==0) break;
}
int num=0;
for(i=0;i<=mod-1;i++){
if(ss[i]!=0)
num++;
}
printf("%10d",step);
printf("%10d",mod);
printf(" ");
if(num==mod)
printf("Good Choice\n");
else
printf("Bad Choice\n");
printf("\n");
}
}
*注意跳出循环的条件 还有把每次算出来的值插入到另一个数组中去。