质数又称素数。指在一个大于1的自然数中,除了1和此整数自身外,没法被其他自然数整除的数。换句话说,只有两个正因数(1和自己)的自然数即为素数。
最小的素数是2, 它也是唯一的偶素数。
比1大但不是素数的数称为合数。
1和0既非素数也非合数。
c prime plus 第七章 7.5程序(这个程序吧1判断为素数,但是1不是哦)
1 // divisors.c -- nested ifs display divisors of a number 2 #include <stdio.h> 3 #include <stdbool.h> 4 int main(void) 5 { 6 unsigned long num; // number to be checked 7 unsigned long div; // potential divisors 8 bool isPrime; // prime flag 9 10 printf("Please enter an integer for analysis; "); 11 printf("Enter q to quit. "); 12 while (scanf("%lu", &num) == 1) 13 { 14 for (div = 2, isPrime= true; (div * div) <= num; div++) 15 { 16 if (num % div == 0) 17 { 18 if ((div * div) != num) 19 printf("%lu is divisible by %lu and %lu. ", 20 num, div, num / div); 21 else 22 printf("%lu is divisible by %lu. ", 23 num, div); 24 isPrime= false; // number is not prime 25 } 26 } 27 if (isPrime) 28 printf("%lu is prime. ", num); 29 printf("Please enter another integer for analysis; "); 30 printf("Enter q to quit. "); 31 } 32 printf("Bye. "); 33 34 return 0; 35 }
OK,下面这个修改一下,不就是列举XX范围内的 素数了么·
1 #include <stdio.h> 2 #include <stdbool.h> 3 int main(void) 4 { 5 unsigned long num; // number to be checked 6 unsigned long div; // potential divisors 7 bool isPrime; // prime flag 8 9 printf("Analysis all the prime till 20: "); 10 11 for(num = 2;num<20;num++) 12 { 13 for (div = 2, isPrime= true; (div * div) <= num; div++) 14 { 15 if (num % div == 0) 16 { 17 18 isPrime= false; // number is not prime 19 } 20 } 21 if (isPrime) printf("%lu is prime ", num); 22 23 } 24 printf("Bye. "); 25 26 return 0; 27 }