dimanche 27 août 2017

Scala speed- Finding Primes example

I was looking at prime numbers with scala. I used the following code to check if a number n is prime.

(2 until n) forall(d=>n%d!=0)

I checked how fast scala will return true for the prime number 179426549.

(2 until 179426549L.toInt) forall(d=>179426549L%d!=0) res22: Boolean = true

Then I tried an even bigger number 32416190071 to see how long it will take to return true for this larger prime.

(2 until 32416190071L.toInt) forall(d=>32416190071L%d!=0) res23: Boolean = true

To my surprise, a return value of true came back for the larger prime much faster. Why is it that the larger number returned a true so much faster?

Aucun commentaire:

Enregistrer un commentaire