Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reto #21 - Java #4349

Merged
merged 1 commit into from
Jul 28, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/*
* Crea un programa que encuentre y muestre todos los pares de números primos
* gemelos en un rango concreto.
* El programa recibirá el rango máximo como número entero positivo.
*
* - Un par de números primos se considera gemelo si la diferencia entre
* ellos es exactamente 2. Por ejemplo (3, 5), (11, 13)
*
* - Ejemplo: Rango 14
* (3, 5), (5, 7), (11, 13)
*/

import java.util.ArrayList;
import java.util.List;

public class LilyMilano {

public static void main(String[] args) {

int max = 33;

List<List<Integer>> twins = getPrimeTwins(max);

System.out.println(twins); // [[3, 5], [5, 7], [11, 13], [17, 19], [29, 31]]

}

public static List<List<Integer>> getPrimeTwins(int max) {

List<List<Integer>> twins = new ArrayList<>();

for (int i = 2; i <= max; i++) {
if (isPrime(i) && isPrime(i + 2)) {
twins.add(List.of(i, i + 2));
}
}

return twins;

}

public static boolean isPrime(int num) {
if (num <= 1) return false;
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) return false;
}
return true;
}

}