Sum of series 1+(2*3)+(4*5*6)+...+ n with iterative implementation?

Asked

Viewed 203 times

1

My code:

I have tried several times to solve this question, but I am not able to make the values not repeat and the sum variable multiplies the values within each index. If anyone can do it and explain it to me I’d appreciate it.

#include <iostream>
using namespace std;

// Dado um inteiro n, encontre a soma da série 1+(2*3)+(4*5*6)+...+ n.

int main()
{
  int i, n, t = 0, soma = 0, resp = 0;

  cout << "Entre com um valor n inteiro: ";
  cin >> n;

  for (i = 1; i <= n; i++) {
    t += i;
    soma += (t*i);
  }

  resp = soma;
  cout << "A soma da sequencia e: " << soma;

  return 0;
}
  • 1

    If n is 8, the result should be 1+(23)+(456)+(78) ) ? Or should we calculate the sum of 8 terms (the first is 1, the second is 23, the third is 456, etc. until the eighth, which is 2930313233343536)?

  • 1

    It should be like your second example

2 answers

1


Can’t make that sum up in a direct way as you’re trying to do.

To solve this problem have a trick, you have to create a function that calculates the first term only instead of it returning the result of the term it must return the sum of this first term with the next term(using the function itself in order to create a string that will always seek the next term of the series).

So that the calculation does not enter into a loop you pass, for the function, a counter of how many terms you want to calculate as well as the number of terms to be calculated:

#include<iostream> 
using namespace std; 


// N = 1 --> 1                                 =     1
// N = 2 --> 1 + (2*3)                         =     7
// N = 3 --> 1 + (2*3) + (4*5*6)               =   127 
// N = 4 --> 1 + (2*3) + (4*5*6) + (7*8*9*10)  =  5167 

int somatorio(int valor, int termos_calculados, int termos)  
{ 
    int i, aux = 1; 
    //Se o número de termos caulculados passar o número de termos exigidos a função retorna 0 
    if (termos_calculados > termos) return 0; 

    //Calcula o term (a * b * c...)
    for (i = valor; i < valor + termos_calculados; i++) 
        aux *= i;  

    return aux + somatorio(i, termos_calculados + 1, termos);  
} 

int main() 
{ 
    int termos;
    cout << "Digite o número de termos na série:"<<endl;
    cin >> termos;  
    cout << "A soma da sequencia e: " << somatorio(1, 1, termos)<<endl;    
    return 0; 
} 

1

I found that this problem is not as simple as it seems, at least to solve in an elegant way. Moreover it is not well defined: what happens when parcels are missing in the last term of the sum ?

Below is a simple solution to the problem. The key is to iterate the number of plots, and then go on consuming the numbers from 1 to the number that was typed.

#include <iostream>
using namespace std;

// dado um inteiro n, encontre a soma da série 1+(2*3)+(4*5*6)+...+ n.

int main()
{
  int n;

  cout << "*\n";
  cout << "* digite uma valor inteiro: ";
  cin >> n;

  // regra de calculo: a cada iteracao i multiplicar os proximos i termos da sequencia
  // se nao houver numeros suficiente no ultimo termo, multiplicar os numeros que existem
  // este caso esta marcado com <-- na tabela abaixo
  // 0 --> 0                       =   0
  // 1 --> 1                       =   1
  // 2 --> 1 + 2                   =   3 <--
  // 3 --> 1 + (2*3)               =   7
  // 4 --> 1 + (2*3) + 4           =  11 <--
  // 5 --> 1 + (2*3) + (4*5)       =  27 <--
  // 6 --> 1 + (2*3) + (4*5*6)     = 127
  // 7 --> 1 + (2*3) + (4*5*6) + 7 = 134 <--

  int total = 0;
  int next_number = 1;

  for (int n_parcelas = 1; next_number <= n; n_parcelas++)
  {
    // valor inicial do termo, tem que ser 1 porque o termo é a multiplicacao de parcelas
    int termo = 1;

    // calcula proximo termo do somatório, com n_parcelas
    for (int i = 0; i < n_parcelas && next_number <= n; i++, next_number++)
    {
      cout << "* n_parcelas: " << n_parcelas << " / next_number: " << next_number;
      termo *= next_number;
      cout << " / termo: " << termo << " / total anterior: " << total << "\n";
    }

    total += termo;
    cout << "* total parcial: " << total << "\n";
  }

  cout << "* total: " << total << "\n";
  cout << "*\n";
}

Below, tests with number from 0 to 5 (tested up to 11, and was right).

[~/Projects/testes/so]
$./377046
*
* digite uma valor inteiro: 0
* total: 0
*

[~/Projects/testes/so]
$./377046
*
* digite uma valor inteiro: 1
* n_parcelas: 1 / next_number: 1 / termo: 1 / total anterior: 0
* total parcial: 1
* total: 1
*

[~/Projects/testes/so]
$./377046
*
* digite uma valor inteiro: 2
* n_parcelas: 1 / next_number: 1 / termo: 1 / total anterior: 0
* total parcial: 1
* n_parcelas: 2 / next_number: 2 / termo: 2 / total anterior: 1
* total parcial: 3
* total: 3
*

[~/Projects/testes/so]
$./377046
*
* digite uma valor inteiro: 3
* n_parcelas: 1 / next_number: 1 / termo: 1 / total anterior: 0
* total parcial: 1
* n_parcelas: 2 / next_number: 2 / termo: 2 / total anterior: 1
* n_parcelas: 2 / next_number: 3 / termo: 6 / total anterior: 1
* total parcial: 7
* total: 7
*

[~/Projects/testes/so]
$./377046
*
* digite uma valor inteiro: 4
* n_parcelas: 1 / next_number: 1 / termo: 1 / total anterior: 0
* total parcial: 1
* n_parcelas: 2 / next_number: 2 / termo: 2 / total anterior: 1
* n_parcelas: 2 / next_number: 3 / termo: 6 / total anterior: 1
* total parcial: 7
* n_parcelas: 3 / next_number: 4 / termo: 4 / total anterior: 7
* total parcial: 11
* total: 11
*

[~/Projects/testes/so]
$./377046
*
* digite uma valor inteiro: 5
* n_parcelas: 1 / next_number: 1 / termo: 1 / total anterior: 0
* total parcial: 1
* n_parcelas: 2 / next_number: 2 / termo: 2 / total anterior: 1
* n_parcelas: 2 / next_number: 3 / termo: 6 / total anterior: 1
* total parcial: 7
* n_parcelas: 3 / next_number: 4 / termo: 4 / total anterior: 7
* n_parcelas: 3 / next_number: 5 / termo: 20 / total anterior: 7
* total parcial: 27
* total: 27
*

[~/Projects/testes/so]
$

UPDATING

Another solution, perhaps easier to understand.

// dado um inteiro n, encontre a soma da série 1+(2*3)+(4*5*6)+...+ n.

#include <iostream>
using namespace std;

#include <stdlib.h> // abs

// ---

static int valor_digitado;

// ---

static int proximo_valor_a_processar()
{
  static int _proximo_valor_a_processar = 1;
  return
    (_proximo_valor_a_processar > valor_digitado) ? 0
      : _proximo_valor_a_processar++;
}

// ---

int main()
{
  cout << "*\n";
  cout << "* digite uma valor inteiro: ";
  cin >> valor_digitado;
  valor_digitado = abs(valor_digitado); // se digitar negativo transforma em positivo

  int total = 0;
  int valor_a_processar = proximo_valor_a_processar();

  for (int n_parcelas = 1; valor_a_processar; n_parcelas++)
  {
    int termo = 1;
    int n_parcela = 0;

    do {
      cout << "* n_parcelas: " << n_parcelas << " / valor_a_processar: " << valor_a_processar;
      termo *= valor_a_processar;
      cout << " / termo: " << termo << " / total anterior: " << total << "\n";
      valor_a_processar = proximo_valor_a_processar();
    }
    while (++n_parcela < n_parcelas && valor_a_processar);

    total += termo;
    cout << "* total parcial: " << total << "\n";
  } // for

  cout << "* total: " << total << "\n";
  cout << "*\n";
}

Browser other questions tagged

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