Back to Problem list
Back to Problem list
Problem 26:
You are given two numbers, A and B, and you have to find the
total of all the numbers between these two numbers.For example
if you are given the numbers 9 and 15, you must find
the sum 9+10+11+12+13+14+15 which is 84.
#include<stdio.h>
int Solution_1(int n, int m) { // Using formula
int total = m - n + 1;
int sum = ((n + m) * total)/2;
return sum;
}
int Solution_2(int n, int m) { // Using loop
int i, sum = 0;
for(i = n; i<=m; i++) {
sum+= i;
}
return sum;
}
int main() {
int n, m;
scanf("%d %d",&n,&m);
printf("%d %d\n",Solution_1(n,m),Solution_2(n,m)); // both gives same answer
return 0;
}
Back to Problem list