求10000以内的素数

2015-05-27

计算一个N值,从2到N遍历取模,如果可以取余,就不是。

1、shell实例

#!/bin/sh

N=$1
if [ -z $1 ];then
echo Usage:$0 num
exit 0
fi

for (( i=2; i<=$N;i++ ));do
flag=0;
for (( j=2;j<=i/2;j++ )); do
if ((i%j==0));then
flag=1;
break;
fi
done
done

if (($flag));then
echo $N is not a prime number;
else
echo $N is a prime number;
fi

2、c实例

#include "stdio.h"

int main(){
int a,b;
int c=10000;

for(a=2;a<=c;a++)
{
for(b=2;b < a;b++) if(a%b==0) break; if(b>=a)
printf("%5d\n",a);
}
return 0;
}

3、python

#!/usr/bin/python

def is_prime(num):
res=True
for x in range(2,num-1):
if num%x==0:
res=False
return res
return res

for x in range(2,1000):
if is_prime(x):
print x

 

或者

 

#!/usr/bin/python
import sys

if __name__ == '__main__':

if len(sys.argv) < 2 :
print "please usage %s string "%(sys.argv[0])
sys.exit()

def is_prime(num):
res=True
for x in range(2,num-1):
if num % x == 0:
res=False
return res

n=int(sys.argv[1])
if is_prime(n):
print("%s is a prime" % (n))
else:
print("%s is not a prime" % (n))

4、c实例

#include "stdio.h"

int main(){
int a,b;
int c=1000;
int d=0;

for(a=300;a<=c;a++)
{
for(b=2;b<a;b++) if(a%b==0) break; if(b>=a)
{
printf("%5d ",a);
d++;
if(d%6==0)
printf("\n");
}
}
printf("\n");
printf("row:%5d ",d/6+1);
printf("\n");
printf("totol:%5d ",d);
printf("\n");
return 0;
}

分类:Linux | 标签: |

相关日志

评论被关闭!