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:

  1. 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.
  2. If n can be divided by any number, it is not a prime number; otherwise, it is prime.

Prime factorization method:

  1. 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.
  2. 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.
  3. If n cannot be divided evenly, continue trying the next number.
  4. Repeat steps 2 and 3 until n equals 1.
  5. 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.

广告
Closing in 10 seconds
bannerAds