In order to determine whether a number is a prime number through C programming, you must first understand what a prime number is. As a form of number, the definition of prime numbers must of course be found in mathematics.
In mathematical theory,When a number greater than 1 has only 1 and itself has two factors, and there are no other factorsThen the number is said to be prime. Conversely, a number is non-prime when there is at least one factor in the numerical range from 1 to itself.
The way to determine a prime number is to use its negative definition, that is, to look for a third factor other than 1 and the number itself, and once it exists, it can be determined that the number is not prime.
Designing a C program to provide the function of determining prime numbers is actually to design an algorithm program according to the mathematical determination method of prime numbers. The algorithm idea is as follows:
First, judge the legitimacy of the value, that is, judge whether it is greater than 1, if it is, it is legal, otherwise it is not legal;
Directly judge whether the target number is 2, if it is, it is a prime number, otherwise make subsequent judgments;
To judge parity, if it is an even number, it must not be a prime number, and if it is an odd number, the next step is to make a judgment;
Determine whether it is divisible by 3 or 5, if yes, it is non-prime, otherwise proceed to the next judgment.
Use a loop to find out if there is a factor in the number between 1 and the target number, if yes, it is a non-prime number, otherwise it is a prime number.
The algorithm is implemented as follows:
The spirit of the algorithm isIf you can't circulate, you won't circulate。Then, in the implementation, for the final loop, the reason why we start with 7 is because the previous 2, 3, and 5 have all been used, and 6 is non-prime, so multiples of 6 must not be prime.