Processing math: 45%
Solutions of Even numbers - MarisaOJ: Marisa Online Judge

Solutions of Even numbers

Select solution language

Write solution here.


omegumunot    Created at    9 likes

Even Numbers

Idea

We want to print all positive even numbers less than or equal to n in descending order.

If we only want to print all positive integers less than or equal to n in descending order, we can use a for loop as follows.

for(int i = n; i > 0; i--) {
    cout << i << " ";
}

Note how we modify the initialization, the condition, and the increment to achieve this. To print all even numbers, we can check if i is even before printing using the % operator.

if(i % 2 == 0) {
    // i is even!
}

However, it is faster and easier (in my opinion) to decrement by 2 in the for loop, removing the need for the if statement.

for(int i = n; i > 0; i -= 2) {
    cout << i << " ";
}

The issue with this is that it doesn’t work when n is odd. So if we set the initialization to be n−nmod, we can ensure that we start at the largest positive even number less than or equal to n. This works because if n is even, n - n \bmod 2 = n, and if n is odd, n - n\bmod 2 = n - 1, which is where we want to start.

Code

#include <bits/stdc++.h>

using namespace std;

using ll = long long;
const int MOD = 1E9 + 7;
const int INF = 1E9; const ll INFLL = 1E18;

int n;

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cin >> n;
    for(int i = n - (n % 2); i > 0; i -= 2) {
        cout << i << " ";
    }
    cout << "\n";
}