Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

159
Visualizações
I am trying to write a code that checks if a number between 2 and 1000 is a prime Number
import java.util.Scanner;

public class Main {

  public static void main(String[] args) {
  
    for(int j = 2; j<=1000; j++) {
        boolean yes = true;
        for(int i = 2; i<j && yes== true; i++){
            if(j%i==0) {
                yes=false;
            }
        System.out.println(j + ":" + yes); 
      } 
    }  
  }
}      

I am trying to understand where is the problem without any answer so far.

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

You need to move System.out.println(j + ":" + yes); out of the inner loop. The reason why you need to move it out is that if the number is prime or not is decided only after the inner loop is finished.

public class Main {
    public static void main(String[] args) {
        for (int j = 2; j <= 1000; j++) {
            boolean yes = true;
            for (int i = 2; i < j && yes == true; i++) {
                if (j % i == 0) {
                    yes = false;
                }
            }
            if (yes) {
                System.out.println(j + ":" + yes);
            }
        }
    }
}

Side note: You are not required to check up to i < j. It can be i <= Math.sqrt(j). Check https://en.wikipedia.org/wiki/Primality_test to learn more about it.

Also, if you want to print the false as well, do not use the if (yes) {} block.

public class Main {
    public static void main(String[] args) {
        for (int j = 2; j <= 1000; j++) {
            boolean yes = true;
            for (int i = 2, n = (int) Math.sqrt(j); i <= n && yes == true; i++) {
                if (j % i == 0) {
                    yes = false;
                }
            }

            System.out.println(j + ":" + yes);

        }
    }
}
over 4 years ago · Santiago Trujillo Relatório

0

This can be done using Streams as follows:

IntStream.range(2, 1001)
         .boxed()
         .filter(j -> IntStream.range(2, j).boxed().allMatch(i -> j % i != 0))
         .forEach(System.out::println);

First, we:

  • generate the indices between 2 to 1000 (inclusive) i.e., IntStream.range(2, 1001),

  • then we convert from IntStream into Integer (i.e., boxed()),

  • then we filter to only the number that are prime

    .filter(j -> IntStream.range(2, j).boxed().allMatch(i -> j % i != 0)),

  • finally we print out the result.

This kind of pipeline is less prone to the mistakes that you have done in your original code.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda