java stream实现勾股定理

x33g5p2x  于2021-11-22 转载在 Java  
字(1.0k)|赞(0)|评价(0)|浏览(443)
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

相关文章

最新文章

更多