Monday, September 22, 2008

Optimal way to check if a given number is prime

Technique:
Prime numbers 2,3,5,7,11,13,17,19,.....
Except for 2 and 3, rest of the prime numbers would be in the form 6n-1 or 6n+1 where n = 1,2,... . The rule is not always true, for instance when n = 4 6n+1 is 25.
Given a number M, check if it is divisible from 2 to the floor of square-root of M.

Example
Suppose the given number is 59, then floor of square root of 59 is 7.
ie try dividing 59 from 2,3,5 and 7.

No comments: