Competitive Programming Solutions

GitHub
back to dashboard

S. Sum of Consecutive Odd Numbers

Codeforces - Sheet #2 (Loops) · limit: 1s · memory: 256MB · view on codeforces

input

3
5 6
10 4
4000 9000

output

0
21
12
Main.java
static void solve() {

        // Write your solution here
        int x = in.nextInt();
        int y = in.nextInt();
        int start = Math.min(x, y);
        int end = Math.max(x, y);
        start++;
        end--;

        if (start % 2 == 0)
            start++;
        if (end % 2 == 0)
            end--;
        

        if (start <= end) {
            long n = ((long) end - start) / 2 + 1;
            long sum = n * ((long) start + end) / 2;
            out.println(sum);
        } else {
            out.println("0");
        }

    }