June 1, 201312 yr Bit more code to share from a little exercise I was doing in Groovy-ness. Returns a list of prime numbers between start and end (max - 2147483647 ) or if no end value is supplied works out if start is prime by returning it, in both case returns false if there are no answers. It get slow with wide ranges or very high numbers but works right the way up the the top. // Primes ( start ; end ) // 13_06_01 JR // v1.0 // returns all primes between start and end // if no value for end just works out if the start is prime // works up to 2147483647 (largest integer) TAKES A LONG TIME UP THERE!! start = start.toInteger() end = !end ? start + 1 : end.toInteger() primes = (start..end).findAll{ it -> (2..<it).every { divisor -> it % divisor != 0 } } primes ?: false /* long way of writing it out.... start = start.toInteger() if (end == null){ end = start + 1 } else { end = end.toInteger() } //end if primes = (start..end).findAll{ it -> (2..<it).every { divisor -> it % divisor != 0 } } if (primes == null){ return false } return primes */
July 1, 201312 yr Hi John You can speed this up fairly easily. You don't need to test all the way to the end of your number range. You can stop as soon as you reach the square root of value in your "end" variable. Bit more code to share from a little exercise I was doing in Groovy-ness. Returns a list of prime numbers between start and end (max - 2147483647 ) or if no end value is supplied works out if start is prime by returning it, in both case returns false if there are no answers. It get slow with wide ranges or very high numbers but works right the way up the the top. // Primes ( start ; end ) // 13_06_01 JR // v1.0 // returns all primes between start and end // if no value for end just works out if the start is prime // works up to 2147483647 (largest integer) TAKES A LONG TIME UP THERE!! start = start.toInteger() end = !end ? start + 1 : end.toInteger() primes = (start..end).findAll{ it -> (2..<it).every { divisor -> it % divisor != 0 } } primes ?: false /* long way of writing it out.... start = start.toInteger() if (end == null){ end = start + 1 } else { end = end.toInteger() } //end if primes = (start..end).findAll{ it -> (2..<it).every { divisor -> it % divisor != 0 } } if (primes == null){ return false } return primes */
Create an account or sign in to comment