Example (4.2) Simple prime number judgment, example 4.2 prime number judgment
Question-example (4.2) Simple prime number judgment |
|
|
Source |
Computing overview of Peking University 06 |
Description |
For natural number n (0 <n <10), determine whether n is a prime number. |
About Input |
Enter only one row and one natural number n (0 <n <10 ). |
About output |
Only one line is output. If n is a prime number, yes is output; otherwise, no is output. |
Example Input |
7 |
Example output |
yes |
Prompt |
There are only four prime numbers between 0 and 10: 2, 3, 5, and 7. |
|
#include <stdio.h>#include <math.h>int isPrime(int n){if(n < 6){if(n == 1 || n == 4){return 0;}else{return 1;}}else /* if(n >= 6) */{int r = n%6;if(r == 1 || r == 5) /* maybe prime */{int d, y;y = (int) sqrt((double) n);for(d = 6; d <= y; d += 6){if(n%(d - 1) == 0 || n%(d + 1) == 0){return 0;}}return 1;}else{return 0;}}}int main(){int n;const char *answer[] = {"no", "yes"};scanf("%d", &n);printf("%s\n", answer[isPrime(n)]);return 0;} |
It is very easy to write and Judge prime numbers using VB.
Not so understandable
For I = 2 To Int (Sqr (n ))
If n Mod I = 0 Then Exit
Next I
This FOR loop is used to determine whether N can be divisible by the previous I = 2 to each number between the N-1
If yes, when the FOR loop ends, I is equal to N + 1. Therefore, we can judge from the if statement that N is a prime number.
IF one of the N mod I is not equal to 0, then it jumps out of the FOR loop, so at this time I must be one of the numbers between I = 2 and the N-1 and then according to judge N is not a prime number
Question: determine the number of prime numbers between-and output all prime numbers.
From the code above, we can see that when sqrt (m,
If the root number cannot be dropped,
There will be decimals,
K is an INT-type container. When sqrt (m) is copied to K, a small number is removed,
Therefore, M + 1 is required to open the root