Groovy Prime Numbers

A little Groovy script to print the first 1000 prime numbers.

def t = 1..1000
def v = []

t.each { n ->
  (2..n).each { d ->
    if (n % d == 0 && n != d)
    v.add(n)
  }
}

println t - v - 1

And another version that’s more verbose but a little faster.

def t = 1..1000
def v = []

for (n = 1 ; n < 1000 ; n++) {
  for (d = 2 ; d < n ; d++) {
    if (n % d == 0 && n != d) {
      v.add(n)
      break
    }
  }
}

println t - v - 1

Leave a Reply