c语言怎么判断质数呀和output factors
prime tester
ake a number from the command line. Do error checking.
If the number is prime, output "the number <> is prime."
If it is not prime, output the factors ("the number <> has the factors <>, <>, <>, <>")
10 - proper functioning
10 - style (esp good naming and breakdown to functions)
#include<stdio.h>
int main()
{
int n,i;
scanf("%d",&n);
if(n<2)
printf("the number %d is not prime.",n);
else
{
for(i=2;i<n;i++)
{
if(n%i==0)
break;
}
if(i==n)
printf("the number %d is prime.",n);
else
{
printf("the number %d has the factors %d",n,i);
i++;
for(;i<n;i++)
{
if(n%i==0)
printf(",%d",i);
}
}
}
}
质数就是这个数不能被从2到这个数减去1的所有整数整除
比如7不能被2到6整除,那么7就是质数;如果能够被某个数整数,这个数就是因子
判断质数有两种方法,一是循环遍历,是否出现1和本身之外的被整除的数,二是采用1~改数的平方根进行遍历是否被整除来判断。第一种方法是定义 第二种方法是数论中的一个结论达到提高算法运算速度的。