Search code examples
c++c++17signed-integer

Doing calculation in the range 0f 10^30


The following code is giving an error by saying the message "singed integer overflow". And the error is in this test case :

input : 208170109961052

Output : 4611790103482368430

Expected Output : 104085054980526

The input range is 1 ≤ n ≤ 10^15

#include "bits/stdc++.h"
using namespace std;

int main()
{
    long long n;
    cin >> n;
    if (n % 2)
    {
        cout << (((n - 1) * (n - 1)) / 4 + (n - 1) / 2) - (((n + 1) / 2) * ((n + 1) / 2)) << '\n';
    }
    else
    {
        cout << ((n * n) / 4 + n / 2) - ((n / 2) * (n / 2)) << '\n';
    }

    return 0;
}

As far as I know long long is the largest datatype. How can I solve this ?


Solution

  • The solution will be to simplify your terms:

    Term 1:

    (((n - 1) * (n - 1)) / 4 + (n - 1) / 2) - (((n + 1) / 2) * ((n + 1) / 2)) 
    
    n^2 - 2n + 1      n - 1            n+1      n+1 
    ------------  +  ------   -   (   ----- *  ----- )
          4             2               2        2
    
    
    n^2 - 2n + 1      n - 1            (n+1)   *  (n+1) 
    ------------  +  ------   -   (   ---------------- )
          4             2                   4
    
    n^2 - 2n + 1      2n - 2              n^2 + 2n -1 
    ------------  +  --------   -   (   ---------------- )
          4             4                      4
          
          
    n^2 - 2n + 1  +    2n - 2    - ( n^2 + 2n -1 )
    ------------------------------------------------ 
                          4                      
                          
    n^2 - 2n + 1  +    2n - 2    -n^2 - 2n + 1 
    ------------------------------------------------ 
                          4                      
                          
        -2n  
    ---------- 
         4    
    
     -n
    ----
      2
      
    

    Term 2

      ((n * n) / 4 + n / 2) - ((n / 2) * (n / 2))
      
        n^2      n          n^2
       ----- +  ---   -  ( ----- )
         4       2           4
         
        n^2      2n         n^2
       ----- +  ---   -    ----- 
         4       4          4
         
        n^2   +   2n    -   n^2
       -------------------------- 
                  4          
                  
        2n
       ---- 
        4          
     
      n 
     --- 
      2
    

    So, If I did no mistake, then the result is always n/2

    Could be done with that:

    #include <iostream> 
    
    int main() {
        long long n{};
        if (std::cin >> n)
            std::cout << ((n%2)? (-n / 2):(n/2)) << '\n';
    }