Reputation: 69
Im creating a simple program in C that user insert a number, for example 5 and the program sums until 5, 0+1+2+3+4. Im using this formula
int sum_naturals(int n){
return (n-1)*n/2;
}
But now i want a formula that can sum from 2 different numbers, like user inserts number 5 and 9 and the program will do 5+6+7+8+9.
Can someone have ideia how can resolve this? Thanks
Upvotes: 2
Views: 274
Reputation: 1
Looks like a simple task, but since you still have problems understanding it, why don't you 'define' your functions first - before 'coding' them.
S(n) = 0 + 1 + 2 + ... + n-1 = n(n-1)/2
F(k,n) = k + k+1 + ... + n-1 + n = -(0 + 1 + ... + k-1) + (0 + 1 + ... + k-1) + k + k+1 + ... + n-1 + n = -S(k) + S(n) + n = S(n+1) - S(k)
Of course, need to assume that k <= n etc.
I guess the reason of all confusion is that you defined your basic function to sum from 0 to n-1, instead of 1 to n.
Upvotes: 0
Reputation: 41017
But now i want a formula that can sum from 2 different numbers,
To find the sum of a certain number of terms of an arithmetic sequence:
#include <stdio.h>
static int sum_naturals(int a, int b)
{
return ((b - a + 1) * (a + b)) / 2;
}
int main(void)
{
printf("%d\n", sum_naturals(5, 9));
return 0;
}
Output:
35
Upvotes: 3
Reputation: 2120
Why not this?
int sum_2_naturals(int n, int m){
return (sum_naturals(m) - sum_naturals(n))
}
Upvotes: 4
Reputation: 180
You can reuse your function
int sum(int a, int b) {
return sum_naturals(b) - sum_naturals(a-1)
}
Of course you have to add some validation.
Upvotes: 6