Sum of numbers in a range C++

Asked

Viewed 192 times

0

I need to make a program with a recursive function that takes two integers as parameters n and m, where n <= m and returns the sum of the numbers in this range.

For example, if n = 1 and m = 4 then the result would be 10: 1 + 2 + 3 + 4.

But I need help being a beginner in programming.

I came to make the following code:

#include <iostream>
using namespace std;
int somanm(int n,int m){
    int s = 1;
    for(int i = 1; i <= m; i++ )
        s = (i(i+1))/2;
    return s;
}
int main(){
    int n, m, s, resul;
    cin >> n >> m;
    resul = somanm(n,m);
    cout << resul;
}

2 answers

3


To better understand how to solve the problem, I recommend reading more about recursiveness. The definition of recursion can be understood as a subroutine (method or function) that can call itself. For the problem presented, a possible solution using recursiveness would be:

int somanm(int n, int m) {
    // Inicialmente, inserimos n + 1
    int soma = n + 1;

    // Caso o mesmo seja menor ou igual a m, podemos prosseguir com seu resultado
    if (soma <= m) {
        // Retornando o valor com a próxima chamada para a mesma função, que vai receber n + 1.
        // Isso pode ser entendido como "andando um item para frente", dado que
        // n + 1 está mais próximo de m do que apenas n.
        return soma + somanm(n + 1, m);
    }

    // Caso não esteja dentro das condições, retornamos apenas 0.
    return 0;
}

Calling the function already adding the n, as it is inclusive:

resul = n + somanm(n, m);

The result of the function somamn for the data 1 and 4 would be:

1
4
10

2

Recursive function of the tail:

// n <= m
int somanm(int n, int m) {
    if (n == m) return n;
    return somanm(n, m - 1) + m;
}

another recursive function:

// n <= m
int somanm(int n, int m) {
    if (n == m) return n;
    int i = (m + n) / 2;
    return somanm(n, i) + somanm(i+1, m);
}

But recursive functions fill in call stack and better use the arithmetic progression in this case:

// n <= m
int somanm(int n, int m) {
    return (n + m) * (m - n + 1) / 2;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.