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

2

I'm trying to solve the 1805 URI question:

  

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 [ A , B      For example, the sum of the natural numbers in the range [2, 5] is 14 = (2 + 3 + 4 + 5).

     

Input

     

Each test case contains two A and B integers (1 ≤ A ≤ B ≤ 10 < sup> 9 ), representing the lower and upper bound respectively.

     

Output

     

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

But it is always giving error:

  

Idonotknowwhat'swrongwiththeresultsbeingthesameasthequestion.

Thecodeisthis:

#include<stdio.h>intmain(intargc,char**argv){longlongintn1,n2,i,j=0;scanf("%lld %lld",&n1,&n2);
    for(i=n1;i<=n2;i++)
    {
        j+=i;
    }
    printf("%lld\n",j);
    return 0;
}
    
asked by anonymous 31.10.2017 / 16:57

1 answer

3

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

Tal as in the sentence :

  

Input

     

Each test case contains two A and B integers (1 ≤ A ≤ B ≤ 10 < sup> 9 ), representing the lower and upper bound respectively.

That is, if the entry is as follows:

1 1000000000

Your program will take a long time to complete. And that's where he blows the time limit. The solution is to look for a solution based on arithmetic progression that eliminates the need to use the for loop, providing the result in a quick time regardless of what input is used.

    
31.10.2017 / 17:10