Last active
May 23, 2020 08:16
-
-
Save paperlefthand/861b5845547d8193c34bff7b0d2213b7 to your computer and use it in GitHub Desktop.
Java Stream API を使って, 100以下の素数を表示させる
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.stream.IntStream; | |
public class Prime { | |
public static void main(String[] args){ | |
// System.out.println(isPrime(51)); | |
primesUnder(100).forEach(x -> System.out.print(x+",")); | |
} | |
private static IntStream primesUnder(int n) { | |
IntStream s = IntStream.range(2,n) | |
.filter(x -> isPrime(x)); | |
return s; | |
} | |
private static boolean isPrime(int n) { | |
if (n<2) {return false;} | |
double m = Math.sqrt((double) n); | |
for (int i=2;i<=m;i++) { | |
if (n%i==0) {return false;} | |
} | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment