Hello, I was wondering where I went wrong in my program, for the goal is to create a program that will determine the number of primes for a pre-determined limit.

The revision in this case, is to ensure that you're finding prime numbers up to, and in including the square root of the limit itself (in this case, the nPrimes was normally equal to 50, but now I want to check for prime numbers up to the square root of 50)

I basically defined another variable to be the square root of 50,

which is roughly 7.0710.

I then changed one of the last statements in the code to ensure that if the squareroot of the number of primes was equal to 0, then the program will break out of the Outer Loop.

The weird thing is, my output is going beyond 7, and giving me prime numbers up to 17.

Any idea on where I went wrong? My revised and new lines from the previous code I had are in bold

Here's my code:

Code:public class Chapt3_Exercise2 { public static void main(String[] args){ /* 2. When testing whether an integer is a prime, it is sufficient to try * to divide by integers up to and including the square root of the number * being tested. Rewrite the program example from this chapter to use this * approach. */ int nPrimes = 50;int sq_of_nPrimes = (int) Math.sqrt(nPrimes);// This sets the number of primes we want to find to be 50 OuterLoop: for(int i = 2 ; ; ++i){ // This is a for loop that will start at 2 since 2 is the // only positive prime number for(int j = 2; j < i; ++j) { // The embedded loop will also continue at 2 but this // for loop will contain the majority of the action if(i % j == 0) { // This checks to see if the remainder from dividing // i's element value by j's element value is 0, meaning // an even number has been found, it will then // continue to the next block of code continue OuterLoop; // This will make it reenter the loop if its a // positive number to increment its i and j element // value AGAIN to make it so that its no longer // an even result (makes sense), so realistically // this loop attempts to go through all the numbers // from 1 to 50, but keeps skipping even numbers that // aren't prime (makes sense actually, though it was // a bit difficult to understand at first // Its just going to keep skipping portions of the loop // until it finds what it wants, and then will // increment the "prime" numbers it finds into a count // aka the nprimes variable } } System.out.println(i); // This just outputs the current value of iif(--sq_of_nPrimes == 0){break OuterLoop; // This will decrement the number of primes until it // reaches zero and then breaks the loop } } // This is where break OuterLoop goes to } }

Tweet This+ 1 thisPost To Linkedin