0

I was wondering why the math formula we use to find the sum of the numbers up to the entered number works in javascript but it doesn't work in c ++.

The Formula: (n/2)*(n+1)

Example:

n = 3;

(1+2+3 = 6) = (3/2 * 3+1)

#include <iostream>

using namespace std;

int sumUp(int n){
    
    return (n/2) *(n+1);
}

int main(){
    
    int a;
    
    cout << "Enter the nth number for Sum." << endl;
    
    cin >> a;
    
    cout << sumUp(a) << endl;
    
    system("pause");
}
  • My Input --> 3
  • My Output --> 4

  • Expected: 6

Is there anyone who can help me?

Mustafa Guner
  • 61
  • 2
  • 8
  • 5
    Note that `3/2 == 1` because integer division truncates. Use `(n*(n+1)) / 2` instead (but watch for integer overflow in case of really large numbers). – dxiv Dec 08 '20 at 23:43
  • 2
    Thank you for editing the question. – cigien Dec 08 '20 at 23:52

0 Answers0