I am lost. I cannot figure out why my prime number java program prints a one. On
ID: 3628016 • Letter: I
Question
I am lost. I cannot figure out why my prime number java program prints a one. One is not prime. Can you help me with this issue by explaining the issues?// Exercise 6.25 Part A and B Solution: PrimeNum.java
// Program calculates prime numbers
public class PrimNum
{
public void findPrimes()
{
System.out.println( "Prime numbers between 1 through 10000 are: " );
// find the prime numbers between 1 and 10,000
for ( int number = 1; number <= 10000; number++ )
if ( isPrime ( number ) )
{
System.out.println( number ); // test all numbers between 2 and 10000
}
} // end method findPrimes
// a helper method for determining if a number is prime
public static boolean isPrime( int n )
{
for( int a = 2; a <= n / 2; a++ )
{
if ( n % a == 0 )
return false;
}
return true;
} // end method isPrime
} // end of PrimNum
// Exercise 6.25 Part A and B Solution: PrimeNumTest.java
// Test application for class PrimeNum
public class PrimeNumTest
{
public static void main( String[] args )
{
PrimNum myPrimNum = new PrimNum();
myPrimNum.findPrimes();
}// end main
}// end class PrimeNumTest
Explanation / Answer
consider the code below :
public static boolean isPrime( int n )
{
for( int a = 2; a <= n / 2; a++ )
{
if ( n % a == 0 )
return false;
}
return true;
} // end method isPrime
_______________________________________________________________
When n = 1, look at the for loop.
n/2 = 1/2 = 0 because n and 2 are integers and you dont get 0.5.
So, the condition a <= 0 will fail because a = 2 and the system exits out of the for loop.
The next statement after that for loop, ie return true is executed.
Of course, that gives wrong results. 1 is not a prime number.
To solve this problem modify the code as show below:
public static boolean isPrime( int n )
{
if(n == 1)
{
return false;
}
for( int a = 2; a <= n / 2; a++ )
{
if ( n % a == 0)
{
return false;
}
}
return true;
} // end method isPrime
} // end of PrimNum
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.