最大整数递归

问题描述 投票:0回答:2

我正在编写一个程序来计算一个数的阶乘。我正在使用递归来解决这个问题。我遇到的问题是,一旦我达到 13 号,由于 INT 的限制,它会抛出垃圾号。我想要做的是实现一种在错误发生时捕获错误的方法(无需硬编码,在 x=13 时它必须停止,而是通过输出)。这是我的尝试:

#include <stdio.h>

int factorial( int n)
{
    printf("Processing factorial( %d )\n", n);

    if (n <= 1)
    {
        printf("Reached base case, returning...\n");
        return 1;
    }
    else
    {
        int counter = n * factorial(n-1);       //Recursion to multiply the lesser numbers

        printf("Receiving results of factorial( %d ) =  %d * %d! = %d\n", n, n, (n-1), counter);

        if( counter/n != factorial(n-2) ) //my attempt at catching the wrong output
        {
            printf("This factorial is too high for this program ");
            return factorial(n-1);
        }
        return counter;


        printf("Doing recursion by calling factorial (%d -1)\n", n);
    }


}


int main()
{
    factorial(15);
}

问题是程序现在永远不会终止。它不断循环并向我抛出随机结果。

由于我无法回答我自己的问题,我将使用我的解决方案进行编辑:

int jFactorial(int n)
{
    if (n <= 1)
    {
        return 1;
    }
    else
    {
        int counter = n *jFactorial(n-1);
        return counter;
    }
}

void check( int n)
{
    int x = 1;
    for(x = 1; x < n+1; x++)
    {
        int result = jFactorial(x);
        int prev = jFactorial(x-1);
        if (((result/x) != prev) || result == 0 )
        {
            printf("The number %d makes function overflow \n", x);
        }
        else
        {
            printf("Result for %d is %d \n", x, result);
        }
    }
}
c factorial ansi-c
2个回答
2
投票

更好的方法:

if (n <= 1) {
   return 1;
} else {
    int prev_fact = factorial(n - 1);
    if (INT_MAX / prev_fact < n) { /* prev_fact * n will overflow */
        printf("Result too big");
        return prev_fact;
    } else {
        return prev_fact * n;
    }
}

使用更准确的检查(我希望)乘法是否会溢出,并且不再添加对

factorial
的调用。


1
投票

更新

仔细观察后,原来我错过了 gmp 也为 C 实现的事实。这是

C

中的解决方案

我已经能够在我的 macbook pro 上运行它,使用 homebrew 安装 gmp (

brew isntall gmp
)

#include <gmp.h>

#include <stdio.h>

void factorial(mpz_t ret, unsigned n) {
  if (n <= 1) {
    mpz_set_ui(ret, 1);//Set the value to 1
  } else {
    //multiply (n-1)! with n
    mpz_t ret_intermediate;
    mpz_init (ret_intermediate);//Initializes to zero
    factorial(ret_intermediate, n-1);
    mpz_mul_ui(ret, ret_intermediate, n);
  }

  return;
}

int main(){
  mpz_t result;
  mpz_init (result);
  factorial(result, 100);
  char * str_result = mpz_get_str(NULL, 10, result);
  printf("%s\n", str_result);
  return 0;
}

原答案

快速谷歌搜索后,我找到了以下解决方案。请注意,这是一个 C++ 解决方案。我在底部简要描述了如何在 ANSI C 中做同样的事情。

C++ 中的大数库

https://gmplib.org/ 这个 c++ 库可以处理任意大的数字。

结帐https://gmplib.org/manual/C_002b_002b-Interface-General.html

整个代码看起来像……

#include <gmpxx.h>

#include <iostream>

mpz_class factorial(unsigned n) {
  if (n <= 1) return mpz_class(1);

  return mpz_class(n) * factorial(n-1);
}

int main(){
  mpz_class result = factorial(100);
  std::string str_result = result.get_str();
  std::cout << str_result << std::endl;
  return 0;
}

ANSI C 版本

你可以使用 ansi C 实现同样的事情,用一个结构来保存扩展的数字列表(使用链表或任何其他可扩展的数组列表容器),你只需要实现三个方法......初始化,乘法和转换为字符串。

© www.soinside.com 2019 - 2024. All rights reserved.