Skip to content

Instantly share code, notes, and snippets.

@paperlefthand
Last active May 23, 2020 08:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paperlefthand/861b5845547d8193c34bff7b0d2213b7 to your computer and use it in GitHub Desktop.
Save paperlefthand/861b5845547d8193c34bff7b0d2213b7 to your computer and use it in GitHub Desktop.
Java Stream API を使って, 100以下の素数を表示させる
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