Jump to content
Claris Engage 2025 - March 25-26 Austin Texas ×

This topic is 4174 days old. Please don't post here. Open a new topic instead.

Recommended Posts

Posted

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
*/
  • 1 month later...
Posted

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
*/

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 account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

By using this site, you agree to our Terms of Use.