Sum of Squares of Even Numbers (Loop vs Streams)
Problem
Read an array. Print the sum of the squares of all even numbers. Solve it once with a loop and once with a filter / map / reduce pipeline.
Constraints
- 1 <= n <= 10^5
- |a[i]| <= 10^5
Examples
Input
6 1 2 3 4 5 6
Output
56
Solutions
The classic way: a loop, an if and a running sum.
/*
* Problem : Process an array.
* Input : n, then n integers.
* Output : The sum of squares of the even numbers.
* Approach: Loop with a condition.
* Time : O(n)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static long solve(int[] a) {
// Step 1: The sum starts at 0. We use long, because squares can be large.
long sum = 0;
// Step 2: Look at every number with a loop.
for (int value : a) {
// Step 3: Only even numbers are used. Add the square of the number.
if (value % 2 == 0) {
sum += (long) value * value;
}
}
return sum;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
int[] a = new int[size];
for (int i = 0; i < size; i++) {
a[i] = scanner.nextInt();
}
System.out.println(solve(a));
}
}
Hints (1)
- Which numbers are used?