C++检测数字是否为素数的源码:
注意:dos 下测试,需要输入参数如: **.exe 1000003
含有字符串判断。
#include <iostream>
#include <math.h>
using namespace std;
bool is_prime(long p)
{
long x = (long)sqrt(p);
long i = 3;
if(p==2)return true;
if(p%2 == 0)return false;
while(i<x+1){
if(p%i == 0)return false;
i+=2;
}
return true;
}
bool is_digit(const char *str)
{
size_t len = strlen(str);
while(len > 0) {
if (*str < '0' || *str > '9') {
return false;
}
str++;
len--;
}
return true;
}
int main(int argc,char** argv)
{
if(argc<2)
{
cout<<"please input a number"<<endl;
return 0;
}
if(is_digit(argv[1]))
{
long num = atol(argv[1]);
if(is_prime(num))
{
cout<<"is a primer"<<endl;
}
else
{
cout<<"is not a primer"<<endl;
}
}else
{
cout<<" input is not a num"<<endl;
}
return 0;
}