Bruno Rodrigues
Bruno Rodrigues

Reputation: 69

Sum in C, from two numbers

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

Answers (4)

Mateusz
Mateusz

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

David Ranieri
David Ranieri

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

More info

Upvotes: 3

Mr. E
Mr. E

Reputation: 2120

Why not this?

 int sum_2_naturals(int n, int m){
    return (sum_naturals(m) - sum_naturals(n))
}

Upvotes: 4

borysfan
borysfan

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

Related Questions