How to calculate prime numbers in the C language?
A common method for finding prime numbers is using the “trial division method” or the “prime factorization method”.
Trial and Error method:
- Firstly, assume the number to be determined is n, start trying to divide n by each number from 2 to the square root of n one by one.
- If n can be divided by any number, it is not a prime number; otherwise, it is prime.
Prime factorization method:
- Firstly, assume the number to be evaluated is n, and start trying to divide n by each number from 2 up to the square root of n.
- If n is divisible, take that number as a prime factor of n, divide n by that number, and then continue to try the next number.
- If n cannot be divided evenly, continue trying the next number.
- Repeat steps 2 and 3 until n equals 1.
- If the prime factorization of a number results in only one prime factor, then the number is prime; otherwise, it is not prime.
Both of these methods can determine whether a number is prime, but the prime factorization method can also identify all the prime factors of a number.