# Square prime numbers up to 50 and then round to nearest integer plz help

• September 6th, 2013, 07:12 PM
JKAA
Square prime numbers up to 50 and then round to nearest integer plz help
What I need to do is square all the prime numbers up to 50 and then round to nearest integer. Here is the code I have so far.

public class Test33
{
public static void main (String[] args)
{
int nValues = 50;

OuterLoop:
for(double i = 2; i <= nValues; ++i)
{
for(double j = 2; j < i; ++j)
{
if(i%j == 0)
{
continue OuterLoop;
}
}
System.out.println( Math.sqrt( i ) );
}
}
}

It squares all the primes, but I can't figure out how to round them. I think I need to use Math.round.
ANY help would be appreciated.
• September 7th, 2013, 08:18 AM
Cornix
Re: Square prime numbers up to 50 and then round to nearest integer plz help
To round a floating point number you simply add 0.5 and typecast to int.
If you want to round the variable "someDouble" you can do:
Code :

`int roundedValue = (int) someDouble + 0.5;`
• September 7th, 2013, 08:21 AM
jps
Re: Square prime numbers up to 50 and then round to nearest integer plz help
Quote:

Originally Posted by JKAA
I think I need to use Math.round.

What happened when you tried?

Welcome to the forum
See the Announcements page for the use of code tags.
• September 7th, 2013, 10:35 AM
helloworld922
Re: Square prime numbers up to 50 and then round to nearest integer plz help
All prime numbers are positive integers. Squaring an integer always results in another integer. Addition of integers always results in integers. I don't see why rounding is required at all.

Your code is using the sqrt() function, which is the inverse of the square operation, which can have non-integer return values for integer input.

Take out a piece of paper and write down what steps you need to take (in plain english, or whatever natural language you are most comfortable using) to accomplish this task.