I need help to calculate the factorial in ascending and descending order in an equation!

Asked

Viewed 477 times

0

I need to resolve this question: Make a program that reads the number of terms and a positive value for X. Calculate and show the value of the following series: * S = (-X2/! 1) (+X3/2! ) (-X4/3! ) (+X5/4! ) (-X6/3! ) (+X7/2! ) (-X8/1! ) (+X9/2! ) (-X10/3! ) (+X11/4!) -...

I have no idea how to make the factor increase and decrease in this way. I started making this code:

  for (int i = 1; i < termos; i++) {
    if (expoente % 2 == 0) { //se o expoente for par, x é negativo...
      x = -x;
    }

    fatorial = calcFat(numFat); //calcula o fatorial do numero...
    expoente++;
  }

So I calculate item by item, but what’s left is just to do the cicular numFat from 1 to 4 and after 4 to 1.

ps: Function created to calculate factorial:

int calcFat(int num) { //calcula o fatorial e retorna seu valor...
  int resultado = num;
  for (int i = (num-1); i > 1; i--) {
    resultado  = resultado * i;
  }
  return resultado;
}

Thanks for the help!

  • One possibility is to define a counter variable and an increment with initial value. Each cycle adds the increment to the counter and if the counter is 1 or 4 you reverse the increment signal (increment = - increment;) the same way you did with variable x.

  • Thanks for the tip!

  • I edited the code of the question by putting some spaces...leave everything stuck, no spaces, it is even more difficult to understand...

2 answers

2


I managed in a way not so practical but functional and solved my problem:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

/*
 * Faça um programa que leia o número de termos e um valor positivo para X. Calcule e mostre o valor
da série a seguir:
 * 
S = -X2 +X3 –X4 +X5 -X6 +X7 -X8 +X9 -X10 +X11 -...
          1!     2!      3!       4!     3!     2!    1!       2!        3!       4!
 */
int main(int argc, char** argv) {
    int termos, x, expoente =2, numFat = 1, fatorial;
    float resp;

    printf("Insira o numero de termos: ");
    scanf("%d", &termos);
    printf("Insira o valor de x: ");
    scanf("%d", &x);

    for(int i = 0; i < termos; i++){

        if(numFat == 4){
            while(1==1){
                 if(expoente % 2 == 0){//se o expoente for par, x é negativo...
                  x = -x;
                  }

                fatorial = calcFat(numFat);//calcula o fatorial do numero...
                resp = resp +((float) powf(x, expoente) / fatorial);
                numFat--;
                expoente++;
                if(i == termos){
                    break;
                }
                i++;
                if(numFat == 1)
                    break;
            }
        }else if(numFat == 1){
            while(1 ==1){

                if(expoente % 2 == 0){//se o expoente for par, x é negativo...
                     x = -x;
                }else if(expoente % 2 != 0){
                    x = fabs(x);
                }

                fatorial = calcFat(numFat);
                resp = resp + ((float)powf(x, expoente) / fatorial);
                numFat++;
                expoente++;
                if(i == termos){
                    break;
                }
                i++;
                if(numFat == 4)
                    break;
            }
        }
    }

    printf("Valor da sequencia: %.2f", resp);

    return (EXIT_SUCCESS);
}

int calcFat(int num){//calcula o fatorial e retorna seu valor...
    int resultado = num;
    for(int i = (num-1); i > 1; i--){
        resultado  = resultado * i;
    }
    return resultado;
}

0

An optimized solution, taking advantage of the details of the problem definition: the value of x alternates from - to +, the exponent starts with 2 and grows, the factorial table is fixed.

#include <math.h>    // pow
#include <stdio.h>
#include <stdlib.h>  // abs

static int fact(int n)
{
  int i, result = 1;
  for (i = 1; i <= n;i++)
    result *= i;
  return result;
}

static int facts[6];

static void initFacts()
{
  facts[0] = fact(1);
  facts[1] = fact(2);
  facts[2] = fact(3);
  facts[3] = fact(4);
  facts[4] = facts[2];
  facts[5] = facts[1];
}

int main()
{
  int i, nTermos, x;
  double exp = 2, result = 0;

  int j = 0; // para indexar facts

  initFacts();

  printf("*\n");
  printf("* numero de termos: ");
  scanf("%d", &nTermos);
  printf("* valor de x: ");
  scanf("%d", &x);
  printf("*\n");

  x = abs(x); // garante que x comeca positivo

  for (i = 0; i < nTermos; i++, exp++)
  {
    x = -x;
    result += pow(x, exp) / facts[j++];
    if (j == 6)
      j = 0;
  }

  printf("* result=%lf\n", result);
  printf("*");
}
  • I don’t know why, but the result made with a calculator doesn’t match your code. However your code will help me optimize mine. Thank you very much!!!

  • there may be some mistake, I didn’t really check very well, but the goal was this: to show that it is possible to write a version simpler to understand and very optimized, in relation to your solution

  • Hmm, looking again, I had forgotten to increment the exponent

  • Yes, thanks for the help! I’m doing some project exercises, and in the future I’ll start to optimize my algorithms. Your logic will help me a lot on this path!

Browser other questions tagged

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