您的位置:首页 > 其它

递归求素数加强版

2015-09-19 13:16 316 查看
以前写过一篇关于递归求素数的代码,

今日想起,发现代码还可以优化, 速度和代码长度上稍微优化了一些
/*
primes recursive with c
older c version at http://winxos.blog.51cto.com/1671107/652371 winxos 2015-9-19
*/
#include <stdio.h>

int isdiv(int a,int b)
{
if(b*b>a) return 0;
if(a%b==0) return 1;
isdiv(a,b+1);
}
int isprime(int n)
{
return n>=2 && !isdiv(n,2);
}
int main()
{
int i;
for(i=1;i<10000;i++)
{
if(isprime(i)==1)
{
printf("%d ",i);
}
}
return 0;
}


因为c语言不支持默认参数传递,导致求素数递归方式需要分成两个函数来完成,要不然就要传递两个参数进去
这样调用起来就会与传统素数判定函数有区别,而且也不好看,所以我这里又设计了一个c++版本,代码更简洁
而且使用起来与传统函数无异,写了两个版本,开 O2 状况下 快速版快一倍左右,因为每次加2
/*
primes recursive with cpp version
older c version at http://winxos.blog.51cto.com/1671107/652371 c can not use default parameter,
so can not use only one function with one parameter
winxos 2015-9-19
*/
#include <iostream>
#include <ctime>
using namespace std;

//fast version
int isprime_fast(int a,int b=3)
{
if(a==2 || a==3) return true;
if(a%2==0 || a%b==0 || a<2) return false;
if(b*b>a)return 1;
isprime_fast(a,b+2);
}

//more pretty and simple
int isprime(int a,int b=2)
{
if(a>1 && b*b>a) return true;
if(a%b==0 || b>a) return false;
isprime(a,b+1);
}

int main()
{
int i,ct=0,st=clock();
for(i=1;i<5000000;i++)
{
if(isprime_fast(i))
{
ct++;
//cout<<i<<" ";
}
}
cout<<"total:"<<ct<<" used:"<<float(clock()-st)/CLOCKS_PER_SEC<<" s."<<endl;
return 0;
}


本文出自 “winxosのcoding world” 博客,请务必保留此出处http://winxos.blog.51cto.com/1671107/1696268
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: