From 1d68e2f2ad59af2b340d6b36d89d691a055736ea Mon Sep 17 00:00:00 2001 From: Jorge Navarro Enamorado <110049286+jorgenavarroenamoradotokio@users.noreply.github.com> Date: Thu, 7 Sep 2023 11:56:04 +0200 Subject: [PATCH] =?UTF-8?q?Reto=20#21=20-=20N=C3=9AMEROS=20PRIMOS=20GEMELO?= =?UTF-8?q?S=20[Media]?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/jorgenavarroenamoradotokio.java" | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 "Retos/Reto #21 - N\303\232MEROS PRIMOS GEMELOS [Media]/java/jorgenavarroenamoradotokio.java" diff --git "a/Retos/Reto #21 - N\303\232MEROS PRIMOS GEMELOS [Media]/java/jorgenavarroenamoradotokio.java" "b/Retos/Reto #21 - N\303\232MEROS PRIMOS GEMELOS [Media]/java/jorgenavarroenamoradotokio.java" new file mode 100644 index 0000000000..7e3b0b7737 --- /dev/null +++ "b/Retos/Reto #21 - N\303\232MEROS PRIMOS GEMELOS [Media]/java/jorgenavarroenamoradotokio.java" @@ -0,0 +1,31 @@ +package com.retos.ej21; + +import java.util.stream.IntStream; + +public class jorgenavarroenamoradotokio { + + public static void main(String[] args) { + int rangoMaximo = 14; // Cambia este valor al rango máximo deseado + + System.out.println("Pares de números primos gemelos en el rango hasta " + rangoMaximo + ":"); + IntStream.rangeClosed(2, rangoMaximo - 2).filter(number -> isPrime(number) && isPrime(number + 2)) + .forEach(number -> System.out.println("(" + number + ", " + (number + 2) + ")")); + } + + public static boolean isPrime(int number) { + if (number <= 1) { + return false; + } + + if (number <= 3) { + return true; + } + + if (number % 2 == 0 || number % 3 == 0) { + return false; + } + + return IntStream.rangeClosed(5, (int) Math.sqrt(number)) + .allMatch(i -> number % i != 0 && number % (i + 2) != 0); + } +}