Created
November 3, 2012 20:02
-
-
Save paganotoni/4008524 to your computer and use it in GitHub Desktop.
Simple Prime Numbers Groovy Script
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env groovy | |
public class PrimeNumberEvaluator { | |
// Evaluates a number looking if its prime or not | |
static boolean isPrime( def number ){ | |
def divisors = [] | |
for( def possibleDivisor in (1..number) ){ | |
if( (number % possibleDivisor) == 0 ){ divisors << possibleDivisor } | |
if( divisors.size() > 2 ){ break } | |
} | |
return divisors.size() <= 2 | |
} | |
static def rangePrimes( def initialNumber, def finalNumber ){ | |
def primes = [] | |
for( def possiblePrime in (initialNumber..finalNumber) ){ | |
if( isPrime( possiblePrime ) ) primes << possiblePrime | |
} | |
return primes | |
} | |
} | |
println PrimeNumberEvaluator.isPrime( 2 ) | |
println PrimeNumberEvaluator.isPrime( 12 ) | |
println PrimeNumberEvaluator.isPrime( 5 ) | |
println PrimeNumberEvaluator.rangePrimes( 2, 10000 ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
One could write
isPrime
a bit simpler: