I have been trying to work my way through Project Euler, and have noticed a handful of problems ask for you to determine a prime number as part of it.
-
I know I can just divide x by 2, 3, 4, 5, …, square root of X and if I get to the square root, I can (safely) assume that the number is prime. Unfortunately this solution seems quite klunky.
-
I’ve looked into better algorithms on how to determine if a number is prime, but get confused fast.
Is there a simple algorithm that can determine if X is prime, and not confuse a mere mortal programmer?
Thanks much!
The first algorithm is quite good and used a lot on Project Euler. If you know the maximum number that you want you can also research Eratosthenes’s sieve.
If you maintain the list of primes you can also refine the first algo to divide only with primes until the square root of the number.
With these two algoritms (dividing and the sieve) you should be able to solve the problems.
Edit: fixed name as noted in comments