质数又称素数。指在一个大于1的自然数中,除了1和此整数自身外,不能被其他自然数(不包括0)整除的数。
#include <stdio.h>
#include <math.h>
#include <conio.h>
int main()
{
int i,m;
printf("please input a number,the input number must be an integer and larger than 1:\n");
scanf("%d",&m);
if (m<2)
return -1;
double num = (int)sqrt((double)m);
for (i = 2;i<=num;i++)
if (m%i==0)break;
if (i>num)
{
printf("is a prime number!");
printf("\n%d",m);
}
else
printf("is not a prime number!");
getch();
return 0;
}
求整数区间内的素数:
#include "math.h"
#include <stdio.h>
#include <conio.h>
void main()
{
int i,j,k,m,leap = 1;
for (i = 11;i <= 100;i++)
{
m = (int)sqrt((double)i);
for (j = 2;j < m;j++)
if (i%j == 0)
{
leap = 0;
break;
}
if (leap)
{
printf("i = %d\n",i);
}
leap = 1;
}
getch();
}
求区间内所有素数的平方根之和:
#include "math.h"
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
void main()
{
int i,j,k,m,leap = 1;
double sum = 0;
printf("请输入一个大于3的整数:\n");
scanf("%d",&k);
if(k <= 3) exit(0);
for (i = 3;i <= k;i++)
{
m = (int)sqrt((double)i);
for (j = 2;j <= m;j++)
if (i%j == 0)
{
leap = 0;
break;
}
if (leap)
{
sum += sqrt((double)i);
printf("i = %d\n",i);
}
leap = 1;
}
printf("sum = %f",sum);
getch();
}