What’s wrong with my code? (URI problem 1805)

Asked

Viewed 569 times

2

I’m trying to solve the 1805 URI issue:

A natural number is a non-negative integer (0, 1, 2, 3, 4, 5,...). Your task in this problem is to calculate the sum of the natural numbers that are present in a given range [To, B] inclusive.

For example, the sum of the natural numbers in the range [2, 5] is 14 = (2+3+4+5).

Entree

Each test case contains two integers To and B (1 ToB 109), representing the lower and the upper limit respectively.

Exit

For each test case, the output consists of a line containing the sum of the natural numbers of the range.

But it’s always a mistake:

Time limit exceeded

I don’t know what’s wrong with the results being equal to the question.

The code is this:

#include <stdio.h>
int main(int argc, char** argv)
{
    long long int n1,n2,i,j=0;
    scanf("%lld %lld",&n1,&n2);
    for(i=n1;i<=n2;i++)
    {
        j+=i;
    }
    printf("%lld\n",j);
    return 0;
}
  • https://pt.meta.stackoverflow.com/a/5485/28595

  • Problem statement: https://www.urionlinejudge.com.br/judge/problems/view/1805

  • 2

    Since you are a novice user and the code is simple, I broke the branch and posted the code as text in the question for you. However, avoid posting code as image.

  • 1

    @vnbrs I understand you put that it is timeout error in the title, but I think the information that this is a timeout error is part of the answer, even more considering that the author of the question emphasizes "that the results are equal that the question", but nothing had talked about the weather.

  • all right, with time I’ll learn over time, thanks for the tips

1 answer

3

The code itself is correct, but it has a very bad performance.

Such as stated above:

Entree

Each test case contains two integers To and B (1 ToB 109), representing the lower and the upper limit respectively.

That is, if the entry is as follows:

1 1000000000

Your program will take a long time to complete. And that’s when it will run out of time. The solution is to look for a solution based on arithmetic progression that eliminates the need to use the loop for, providing the result in a fast time regardless of which input is used.

  • Further details: 10 9 does not require long long int , as in a 32-bit integer (usually int, but sometimes on older platforms long int).

  • 1

    @Jeffersonquesado Remember that he will still add up all these factors. The result is that in the case of 1 to 10 9, the sum is 500,000,000,500,000,000, which bursts a 32-bit integer.

  • well perceived. I worried only with the entrance, I forgot the calculations

Browser other questions tagged

You are not signed in. Login or sign up in order to post.