Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

150
Views
Estoy tratando de escribir un código que verifique si un número entre 2 y 1000 es un número primo
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); } } } }

Estoy tratando de entender dónde está el problema sin ninguna respuesta hasta ahora.

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Debe mover System.out.println(j + ":" + yes); fuera del bucle interior. La razón por la que necesita moverlo es que si el número es primo o no, se decide solo después de que finaliza el ciclo interno.

 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); } } } }

Nota al margen: no es necesario que verifique hasta i < j . Puede ser i <= Math.sqrt(j) . Consulte https://en.wikipedia.org/wiki/Primality_test para obtener más información al respecto.

Además, si también desea imprimir el false , no use el bloque if (yes) {} .

 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 Report

0

Esto se puede hacer usando Streams de la siguiente manera:

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

Primero nosotros:

  • generar los índices entre 2 y 1000 (inclusive) , es decir, IntStream.range(2, 1001) ,

  • luego convertimos de IntStream a Integer ( es decir, en boxed() ),

  • luego filtramos solo a los números que son primos

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

  • finalmente imprimimos el resultado.

Este tipo de tubería es menos propensa a los errores que ha cometido en su código original.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!