Reputation: 11
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:
Upvotes: 0
Views: 99
Reputation: 618
@Paul Stoner write you your code that's work.
I suggest an optimization.
numOne
and increment by 2, implicit excluding all evensin this way
private static void findPrimes(int start, int end) {
for (int number = start % 2 == 0 ? start + 1 : start + 2; number <= end; number += 2) {
boolean hasDivisor = false;
for (int divisor = 3; divisor < number && !hasDivisor; divisor+=2) {
hasDivisor = number % divisor == 0;
}
if (!hasDivisor) {
System.out.println(number);
}
}
}
Upvotes: 0
Reputation: 1512
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.
Upvotes: 0