Welcome to the Java Programming Forums

The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

>> REGISTER NOW TO START POSTING

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

1. ## 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.

2. ## 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:
`int roundedValue = (int) someDouble + 0.5;`

3. ## Re: Square prime numbers up to 50 and then round to nearest integer plz help

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.

4. ## 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.