I'm having trouble writing a program that finds the prime numbers between 2-50. My program right now finds "mostly" prime numbers but some non-prime numbers are included. I know there are way more effective methods and strategies for finding prime numbers but I'm trying to first run through every possibility before i move onto more efficient and effective strategies. The way the program is written now if it does find a prime number it prints it multiple times when I only want it to be printed once. Is my program conceptually correct or is my rationale flawed. Why does my program mostly find prime numbers but throw in some non prime numbers? Why does my program print the prime numbers multiple times?
Here is my approach to the problem.
create a for loop to represent potential prime numbers between 2-50. Represent these potential prime numbers by the variable "i". This loop will count down from 50.
Since a number is prime only if there are no other divisible numbers besides itself and 1, i want to create a inner for loop to divide i by every possible number between 2 and i -1 to see if any of these numbers divides evenly into i. Represent these possible divisors by the variable j. If at any point j does divides evenly into i it's not a prime number so I want my inner loop to exit.
If i gets divided by all the numbers of j and there are no numbers that divide evenly into i then that number if prime and want to print that number.
*
import acm.program.*;
public class PrimeNumber extends ConsoleProgram{
public void run(){
for (int i =50; i >= 2; i--){
for (int j= 2; j < i-1; j++){
if (i % j >= 1){
println(i);
}else{
if (i % j == 0) break;
}
} /*end of inner loop */
} /* end of for loop */
} /* end of run method */
}