0
package mypackage;


import java.util.Scanner;

public class twinPrimes {

    public static void main(String[] args){

        int userNum = 0;
        int attemptCount = 0;

        while (userNum < 3){
            System.out.println("Please enter an integer greather than three.");
            Scanner in = new Scanner(System.in);
            userNum = in.nextInt();
            attemptCount++;

            if (attemptCount == 3){
                System.exit(1);
            }
        }

        int count = userNum;

        for (int i = 3; i < count; i++){
            if (isPrime(i)){
                System.out.println(i + " is a Prime Number");
            }
        }


    }

    public static boolean isPrime(int num){
        boolean prime = true;
        int range = (num);

        for (int i = 3; i < range; i++ ){
            if (num % i == 0 ){
                prime = false;
                break;
            }

        }

        return prime;
    }




}

My code here reads a users input greather than or equal to three. (As per the assignment requirment). The only problem I am having is that when I run the code (Say the user enters 13), it returns 3 4 5 7 11. Every other number is correct, but I can't for the life of me figure out why it keeps returning a 4. Any tips/advice? Thanks!

Edited by bigredaltoid

2
Contributors
2
Replies
3
Views
5 Years
Discussion Span
Last Post by bigredaltoid
0
for (int i = 3; i < range; i++ ){
    if (num % i == 0 ){
        prime = false;
        break;
    }
}

hint: for checking if the number is prime why does the condition here start with 3?

0

Ahh I see now, feels like a silly mistake when I see how minor of a change it is. Thank you!

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.