-->
当前位置:首页 > 题库

PROGRAMMING:Judge whether a number is prime or not

Luz5年前 (2021-05-10)题库563
The so-called prime number is a positive integer which can not be divided by any other integer except 1 and itself. 2 is the smallest prime number< br>
Now, the user enters an integer to determine whether it is a prime.
###Input format:
An integer n (n is int).
###Output format:
If n is a prime, output n is a prime. Otherwise, output n is not a prime.
###Input sample 1:
```in
seven
```
###Output sample 1:
```out
7 is a prime.
```
###Input sample 2:
```in
twenty-eight
```
###Output sample 2:
```out
28 is not a prime.
```
###Input sample 3:
```in
one
```
###Output sample 3:
```out
1 is not a prime.
```
###Input sample 4:
```in
-11
```
###Output sample 4:
```out
-11 is not a prime.
```







answer:If there is no answer, please comment
Obviously, the simplest way to judge whether a number is a prime number is to use the formula of prime number. First, n should be greater than 1. Secondly, let the variable I start from 2 until n-1. As long as n is divisible by I once in the cycle, it means that n is not prime. At this time, there is no need to continue to try other factors and exit the cycle directly< br>
It can be found that there are two ways to exit the cycle. One is to find the factor I that can divide N and exit the cycle by breaking. The other is to exit the cycle when I have changed to N and do not meet the cycle conditions. The former means that n is not a prime, and because it is exited by break in the middle of the loop, I must be < = n-1 at this time; The latter means that n is a prime, and I is exactly n. Therefore, you can judge how to exit the loop according to I = = n or I < = n-1, and output accordingly< br>
In fact, I only need to try from 2 to sqrt (n), and the number of cycles can be greatly reduced. At this time, the basis for judging which way the program exits from the cycle will also change accordingly.