Count the Odds

Limits: 250ms, 512 MB

Sometimes, contestants tend to look for patterns in problem descriptions. They try to figure out the setter for a problem from the writing style of a description. Some setters try to write bigger stories, others may write a 2-liner. Let’s have a short description today!


This is a companion discussion topic for the original entry at https://toph.co/p/count-the-odds

odd = []
a,b=map(int,input().split())
for i in range(a,b+1):
if i%2 != 0:
odd += [i]

print(len(odd))

what is the problem in this program?

it show “Preformatted text Too slow! Your submission took too long to finish.”

#include <iostream>
int main()
{
    long long int A, B, x, out;
    std::cin >> A >> B;
    out = 0;

    for(x = A; x<=B; x++){
        if(x%2!=0){
            out++;
        }
    }
    std::cout << "\n" << out;
    return 0;
}

Why is this wrong?

You should print the newline after printing the answer. Not before the answer.

You can easily find that when A is odd, the odd number between A and B is (B - A) // 2 + 1, and when A is even, the odd number between A and B is (B - A + 1) // 2. So It can be an algorithms with O(1) time complexity. If you use for loop, it’s time complexity is O(B-A). Here is my solution using Python 3.

#!/usr/bin/env python
# -*- coding: utf-8 -*-

if __name__ == '__main__':
    a, b = map(int, input().strip().split())

    if a % 2 == 1:
        print((b - a) // 2 + 1)
    else:
        print((b - a + 1) // 2)

Hello, Community!

I’ve been trying to solve this problem with JavaScript and can’t figure out why I am getting WA. Tried to solve it with CPP and got AC. But the similar code doesn’t work when I write in JS.

Any insight will be helpful!

My AC cpp code can be found here and my WA JS code can be found here.

Hey @shamin_asfaq

Thank you for bringing this to our attention. Looks like all of your attempts were correct and the issue was with one of the test cases having an extra empty line at the end. The extra line was causing the ‘line’ event to fire twice. And, so your code was trying to print two answers.

We have fixed the erratic test case and rejudged all of your JavaScript submissions for this problem.

1 Like