得到随机素数

来源:互联网 发布:轩辕剑1 知乎 编辑:程序博客网 时间:2024/05/01 15:33

今天看到一个要求得到随机素数的帖子

http://community.csdn.net/Expert/topic/5449/5449594.xml?temp=.3767969

贴上几个答案 :)

 

jixingzhong(瞌睡虫·星辰) ( 四星(高级)
建议方法:

使用素数表,
随机数生成为 这个素数表索引,
得到的就是一个随即素数 ·········

#define LEN=??

int PTable[LEN]={2,3,5,7,11,...};

srand(time(NULL));
int index=rand()%LEN;

得到的随即素数为: PTable[index] 即是。 

hzhiyang84() ( 一级(初级))

根据需要的素数所在的范围,可以更改RANGE的值,我这里定义为100
由于素数的个数本来就相对比较少,所以程序要执行的时间比较长.


#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#define  RANGE100
int IsPrime(int i);

void  main()
{
   int iPrime = 0;
  
   while(1)
   {  
srand((unsigned)time(NULL));
iPrime = rand()%RANGE;    //得到随机数
if(IsPrime(iPrime)) //判断是否为素数,若为素数,则退出循环,否则继续取随机数
break;
   }
   printf("%d",iPrime);
}

int IsPrime(int iPrime)
{
int i = 0;

if(iPrime < 2)
{
return 0;
}
else
{
for(i=2;i<sqrt(iPrime);i++)
{
if(iPrime%i == 0)  //只要从2到sqrt(iPrime)中有一个数可以被iPrime整除,则iPrime非素数
return 0;
}
}
return 1;
}