天天看点

java stream实现勾股定理

public class RangeTest {
  public static void main(String[] args) {
    Stream<int[]> pythagoreanTriples = IntStream.rangeClosed(1, 100)
                .boxed()
        .flatMap(
                a -> IntStream.rangeClosed(a, 100)
                                .filter(b -> Math.sqrt(a * a + b * b) % 1 == 0)
                                .mapToObj(b -> new int[]{a, b, (int) Math.sqrt(a * a + b * b)}));

     pythagoreanTriples.limit(5)
             .forEach(t->System.out.println("t1="+t[0]+",t2="+t[1]+",t3="+t[2]));

     System.out.println("==================");

     Stream<double[]> p2=IntStream.rangeClosed(1,100)
             .boxed()
             .flatMap(a->
                     IntStream.rangeClosed(1,100)
                             .mapToObj(b->new double[]{a,b,Math.sqrt(a*a+b*b)})
                             .filter(t->t[2]%1==0));

     p2.limit(5).forEach(
             t->System.out.println("t1="+t[0]+",t2="+t[1]+",t3="+t[2])
     );

  }
  
}      
t1=3,t2=4,t3=5
t1=5,t2=12,t3=13
t1=6,t2=8,t3=10
t1=7,t2=24,t3=25
t1=8,t2=15,t3=17
==================
t1=3.0,t2=4.0,t3=5.0
t1=4.0,t2=3.0,t3=5.0
t1=5.0,t2=12.0,t3=13.0
t1=6.0,t2=8.0,t3=10.0
t1=7.0,t2=24.0,t3=25.0