0

I'm working on a program that determines if a number is prime or not.

This involves dividing this number by all numbers smaller than it. But because we are dealing with very large numbers. Dividing it with too many numbers isn't a good idea . So I need a way to minimize the effort done by the program.


Lets assume the number is called $n$. My approach is to divide it by all numbers less than $\frac{n}{2}$.(rounded to the nearest integer) Is there anything wrong with it? And if there is a simpler way please point me to it.
Micah
  • 38,108
  • 15
  • 85
  • 133
Mohammad
  • 357
  • Though they may seem alike, the two questions are really different. I know how to determine if a number is prime but the problem is how to minimize the number of divisions. – Mohammad Dec 01 '13 at 15:41

1 Answers1

0

There are lots of ways to do this, some more complicated than others. You can optimize your method a bit more. You only need to test all integers less than or equal to $\sqrt{n}$, which is smaller than $\frac{n}{2}$ for $n > 2$. You can also use facts like "all primes larger than $2$ are odd", or "all primes larger than 3 are of the form $6k \pm 1$" to test fewer numbers".

There are ways of being "pretty certain" a number is prime, but it's usually overkill. The Miller-Rabin test is pretty easy to implement and works well.

Henry Swanson
  • 12,972