一道简单的acm题目,可是老是超时!!!

eks_222 2008-07-22 02:15:23
问题是这样的
Background

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.


Example

Input



24
39
0
Output

6
3

我的代码如下
#include<iostream.h>
#include<time.h>
int fun(int a)
{
return a/1000+(a-(a/1000)*1000)/100+(a-(a/100)*100)/10+a%10;
}
int main()
{

int a;
while(cin>>a)
{
if(a==0)
break;
else
{
int b=fun(a);
while(b>10||a%b!=0)
{
b=fun(b);
}
cout<<b<<endl;
}
}

return 0;
}



时间和空间限制是Time limit: 1 Seconds Memory limit: 32768K
不知道为什么提交上去的时候老是提示超时!!!!!
用time.h的clock()粗略测试没有超时......
...全文
263 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
1楼给的提示很有意思:
记n=a[k]*10^k+a[k-1]*10^(k-1)+...+a[1]*10+a[0]
原题就是要求(a[k]+a[k-1]+...+a[1]+a[0]) mod 10,如果a[k]+a[k-1]+...+a[1]+a[0]这个和值大于10,那么对和值重复这个过程。
利用10^k mod 9=1这个结论,于是就有
(a[k]*10^k+a[k-1]*10^(k-1)+...+a[1]*10+a[0]) nod 9 == (a[k]+a[k-1]+...+a[1]+a[0]) mod 9
对于t<9的正整数,t mod 9= t mod 10
对于t=9,当t mod 9=0的时候取9,实际上还是在取t mod 10
所以“此题所谓的"digital root"就等于其除以9的余数(余数为0的话,取9)”就可以了。
ecchi 2008-07-22
  • 打赏
  • 举报
回复
LZ你的做法都是错的吧.
另外题目可没说int足够用了, 这题是要高精度的.
POJ上一高人给出的做法:

#include "stdio.h"
#include "string.h"

char num[10000];

int main()
{
int n,l;
while(scanf("%s",num)&&strcmp(num,"0")!=0){
l=strlen(num);
n=0;
int i;
for(i=0;i<l;i++){
n+=num[i]-48;
}
printf("%d\n",(n-1)%9+1);
}

return 0;
}
ndsl3334 2008-07-22
  • 打赏
  • 举报
回复

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

int main()
{

string a; //代替int a

while(cin >> a)
{
if (a == "0")
break;
else
{
int b = 0;

for(int i = 0; i < a.size(); i++)
b += a[i] - '0';
int n = b;
while(true)
{
int i = n, b = 0;
while(i)
{
b += i % 10;
i /= 10;
}
if(0 <= b && b < 10)
{
cout << b << endl;
break;
}
else
n = b;
}
}

}

return 0;
}
yvhkpgf 2008-07-22
  • 打赏
  • 举报
回复
学习了,居然还是这样
deng2000 2008-07-22
  • 打赏
  • 举报
回复
提示楼主: 此题所谓的"digital root"就等于其除以9的余数(余数为0的话,取9).

33,008

社区成员

发帖
与我相关
我的任务
社区描述
数据结构与算法相关内容讨论专区
社区管理员
  • 数据结构与算法社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧