john renfrew Posted June 1, 2013 Posted June 1, 2013 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 */
_ian Posted July 1, 2013 Posted July 1, 2013 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 */
Recommended Posts
This topic is 4174 days old. Please don't post here. Open a new topic instead.
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now