Tuesday, 5 September 2017

java - sum of cubes of first n even/odd numbers

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
import java.util.stream.LongStream;

public class _Math2 {
    public static long sum_of_cubes_of_first_n_even_numbers(int n) {
        return (long) LongStream.iterate(2, i -> i + 2).limit(n).mapToDouble(i -> Math.pow(i, 3)).sum();
    }

    public static long sum_of_cubes_of_first_n_odd_numbers(int n) {
        return (long) LongStream.iterate(1, i -> i + 2).limit(n).mapToDouble(i -> Math.pow(i, 3)).sum();
    }
}

styled using hilite.me

No comments:

Post a Comment