1
Sum of 1 to N
Problem Solving
Formula: (n * (n + 1)) / 2
int n = 100;
cout << (n * (n + 1)) / 2; // 5050
Note: If N is big, use long long (n * (n + 1) can overflow int).
long long n = 100000;
cout << (n * (n + 1)) / 2; // 5000050000
int n = 100, sum = 0;
for(int i = 1; i <= n; i++)
sum += i;
cout << sum;
int sum(int n){
if(n == 0) return 0;
return n + sum(n - 1);
}