Print Even Numbers from 1 to N
Solve this ProblemEasy5–10 min
Topics
BasicsLoops
Companies
TCSInfosysWipro
Given a non-negative integer
n, return every even number from 1 up to and including n, in increasing order.
The check-every-numberCheck Every NumberWalking through every integer from 1 to n and testing i % 2 == 0 before deciding whether to keep it. version is the direct reading of "even numbers up to n" — test everything, keep what qualifies. The step-by-2Step by 2Starting at the first even number and incrementing by 2 each time, so every value visited is already known to be even. version realizes that half the work is wasted checking numbers that were never going to qualify, and skips them by construction instead.
Test Case 1:
Input:n = 10
Output:[2, 4, 6, 8, 10]
Explanation:Every even number from 1 up to 10.
Test Case 2:
Input:n = 1
Output:[]
Explanation:No even numbers between 1 and 1.
Test Case 3:
Input:n = 2
Output:[2]
Explanation:The only even number up to 2.
Constraints
- ◆
0 ≤ n ≤ 1000
Try the Dry Run
Approach & Solutions
Check Every Number with % 2Good
Walk i through every number from 1 to n, and test each one with i % 2 == 0 before deciding whether to keep it. Simple, but it spends a check on every single number, including the roughly half that get thrown away.
Time
O(n)Space
O(n/2) for the outputJava
1class Solution {
2 public int[] printEvenNumbers(int n) {
3 List<Integer> evens = new ArrayList<>();
4 for (int i = 1; i <= n; i++) {
5 if (i % 2 == 0) {
6 evens.add(i);
7 }
8 }
9 int[] result = new int[evens.size()];
10 for (int k = 0; k < evens.size(); k++) {
11 result[k] = evens.get(k);
12 }
13 return result;
14 }
15}Step by 2 from the StartOptimal
Skip the odd numbers entirely instead of checking and rejecting them: start i at 2 (the first even number) and jump by 2 every time. Every value the loop ever visits is already even, so there's no modulo check needed at all, and the loop runs about half as many times.
Time
O(n/2)Space
O(n/2)Java
1class Solution {
2 public int[] printEvenNumbers(int n) {
3 List<Integer> evens = new ArrayList<>();
4 for (int i = 2; i <= n; i += 2) {
5 evens.add(i);
6 }
7 int[] result = new int[evens.size()];
8 for (int k = 0; k < evens.size(); k++) {
9 result[k] = evens.get(k);
10 }
11 return result;
12 }
13}