Online Judge | Problem Set | Authors | Online Contests | User | ||||||
---|---|---|---|---|---|---|---|---|---|---|
Web Board Home Page F.A.Qs Statistical Charts | Current Contest Past Contests Scheduled Contests Award Contest |
吐血 没改之前计算99999999这个数据用了2s多,改了之后只用了16ms,相差甚大啊这个是AC的代码(暴力滴,AC耗时47ms): #include<iostream> #include<cstdio> #include<cstring> #include<cmath> #include<queue> using namespace std; int cut(int m) /* 计算组成一个数的各个数字的和*/ { int k = 0; while(m) { k += m%10; m/=10; } return k; } bool isprime(int m) { if(m==1) return false; if(m==2) return true; for(int i=2;i<=(int)sqrt(m+0.5)+1;i++) { if(m%i==0) return false; } return true; } int prime_factor_sum (int m) { int k = 0; queue<int>q; for(int i=2;m!=1||m!=0;) { if(m%i==0&&isprime(i)) { q.push(i); m/=i; if(isprime(m)) { q.push(m);break; } } else i++; } int s; while(!q.empty()) { s= q.front(); q.pop(); k += cut(s); } return k; } int main() { int n,sum; while(scanf("%d",&n)!=EOF&&n) { while(1) { ++n; if(isprime(n)) continue; sum = cut(n); if(sum == prime_factor_sum(n)) { break; } } printf("%d\n",n); } return 0; } 原来的超时程序只有isprime()函数不同,代码如下: bool isprime(int m) { if(m==1) return false; if(m==2) return true; for(int i=2;i<=m/2+1;i++) { if(m%i==0) return false; } return true; } 把for(int i=2;i<=m/2+1;i++)改成for(int i=2;i<=(int)sqrt(m+0.5)+1;i++)就AC了,无语吧 O(∩_∩)O哈哈~ Followed by: Post your reply here: |
All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator