USACO chapter 1 section 1..5 SuperPrime Rib

USER: tianbing tianbing [tbbd4261]
TASK: sprime
LANG: C++
Compiling...
Compile: OK
Executing...
Test 1: TEST OK [0.011 secs, 2932 KB]
Test 2: TEST OK [0.000 secs, 2932 KB]
Test 3: TEST OK [0.000 secs, 2932 KB]
Test 4: TEST OK [0.011 secs, 2932 KB]
Test 5: TEST OK [0.011 secs, 2932 KB]
All tests OK.

Your program ('sprime') produced all correct answers! This is your submission #7 for this problem. Congratulations!

Here are the test data inputs:

------- test 1 -------
4
------- test 2 -------
5
------- test 3 -------
6
------- test 4 -------
7
------- test 5 -------
8
Keep up the good work!

Thanks for your submission!

代码:原来写的代码在怎么优化只能过四组数据。
             查了一下才知道素数有如下规律:
(来自NOCOW)            

从数学的角度:
1.首位只能是质数2 3 5 7

2.其余位只能是1,3,7,9

3.若n=1,直接输出2,3,5 ,7
这样很快的就过了

/*
ID:tbbd4261
PROG:sprime
LANG:C++
*/

#include
<iostream>
#include
<fstream>
#include
<cmath>
#include
<time.h>
using namespace std;
int n;
int isprime(int n)
{   
if(n<2)return 0;
    
if(n==2)return 1;
    
if(n%2==0)return 0;
    
for(int i=3; i<=sqrt(n); i+=2)
      
if(n%i==0)return 0;
    
return 1;
}

void dfs(int s,int k,ofstream &cout)
{
 
int i;
 
if(!isprime(s))return;
 
if(k==n)cout<<s<<endl;
 
else for(i=1; i<=9; i+=2)
       dfs(s
*10+i,k+1,cout);
}

int main()
{
    ifstream cin(
"sprime.in");
    ofstream cout(
"sprime.out");
   
int t1=1,t2;
   cin
>>n;
   dfs(
2,1,cout);dfs(3,1,cout);dfs(5,1,cout);dfs(7,1,cout);
  
   
//system("pause");
    return 0;
}

 

posted on 2010-06-07 23:17 田兵 阅读(132) 评论(0)  编辑 收藏 引用 所属分类: USACO


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


<2010年6月>
303112345
6789101112
13141516171819
20212223242526
27282930123
45678910

导航

统计

常用链接

留言簿(2)

随笔分类(65)

随笔档案(65)

文章档案(2)

ACM

搜索

积分与排名

最新随笔

最新评论

阅读排行榜