Prime number JAVA

Asked

Viewed 202 times

1

I have to create an algorithm in java to detect the prime numbers in a range that the user choose for example "the existing numbers from 1 to 50" the result is coming out correct in the eclipse console but it keeps repeating several times the answer (1,1,1,1,1,1,3,3,3,3,3,3,3,5,5,5,5,5) e assim por diante.

import java.util.Scanner;

public class EXC29 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner scan = new Scanner(System.in);
        
        System.out.println("Entre com um numero ");
        int num = scan.nextInt();
        
        for(int i = 1;i<=num;i++) {
            
            boolean primo = true;
            
            for(int j = 2;j<i;j++) {
                
                if(i%j == 0) {
                    primo = false;
                }
                
                if(primo) {
                    System.out.println(i);
                }
            }
            
        }
    }

}

1 answer

2


For your code to work without printing repeated numbers just move the last if out of the innermost loop. Also note that 1 is not a prime number, so you should get the outer loop of number 2:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);       
        System.out.println("Entre com um numero ");
        int num = scan.nextInt();       
        for(int i = 2; i <= num; i++) {
            boolean primo = true;        
            for(int j = 2; j < i; j++) {            
                if(i % j == 0) {
                    primo = false;
                }
            }
            if(primo) {
                System.out.println(i);
            }          
        }
    }
}

Watch it work on Ideone.com

That being said, this is a naive quadratic time algorithm. As this has college work face I would recommend the implementation of the classic Sieve of Eratosthenes, or even a more modern algorithm like the Sieve of Atkin.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.