I tried creating a program to find prime numbers within a range. The user is asked to input two numbers then the goal of the program will be to print out the prime numbers between the first number and the last number.
Here's my code below:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// program to check prime numbers b/w two numbers
Scanner sc = new Scanner(System.in);
byte factorsCount = 0;
System.out.println("Enter first number: ");
int numOne = sc.nextInt();
System.out.println("Enter second number: ");
int numTwo = sc.nextInt();
System.out.println("The prime numbers are: ");
for (int i = numOne+1; i < numTwo; i++) {
for (int j = 1; j <= i; j++) {
if (i%j == 0) {
factorsCount++;
}
}
if (factorsCount == 2) {
System.out.println(i);
}
}
}
}
The problem is that the program is not working as intended. For some numOne and numTwo it prints some prime numbers whilst for others it prints nothing
The way I intended for it to work is as follows:
Here is a working copy of your code
package com.goodyear;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// program to check prime numbers b/w two numbers
Scanner sc = new Scanner(System.in);
byte factorsCount = 0;
System.out.println("Enter first number: ");
int numOne = sc.nextInt();
System.out.println("Enter second number: ");
int numTwo = sc.nextInt();
System.out.println("The prime numbers are: ");
for (int i = numOne+1; i < numTwo; i++) {
for (int j = 1; j <= i; j++) {
if (i%j == 0) {
factorsCount++;
}
}
if (factorsCount == 2) {
System.out.println(i);
}
factorsCount = 0;
}
}
}
Resetting the factorCount
variable after evaluation allows for the next evaluation to occur as designed. Also, consider making you evaluation inclusive on numOne
and numTwo
by changing your loop variables.