Sum of n integers 1 + 2 + 3 + ... + n = n * (n + 1) / 2
Sum of the First n Natural Numbers. We prove the formula 1+ 2+ ... + n = n(n+1) / 2, for n a natural number
//Created by https://ashif.in
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin>>n; //Take Input
int sum = n*(n+1)/2; //Calculate Sum
cout<<sum; //Print Sum
return 0;
}
# Not used any loop:
# Time complexity = O(1)
# Space Complexity = O(1)
# n = 10
n = int(input())
print("N-th only even numbers sum =",(n//2)*((n//2)+1))
print("N-th only odd numbers sum =",(n//2)**2)
print("N-th all numbers sum =",n*(n+1)//2)
#output:
# N-th only even numbers sum = 30
# N-th only odd numbers sum = 25
# N-th all numbers sum = 55
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n;
int sum=0;
cin>>n;
for(int i=1;i<=n;i++)
{
sum+=i;
}
cout<<sum<<" ";
cout<<endl;
return 0;
}