递归的问题

aqige_20070720 2007-09-06 12:24:44
package com.hx.test;

public class Test {
public Test() {
}

public int f(int n) {
if (n == 0) {
return 1;
}
return n * f(n - 1);
}

public static void main(String[] args) {
Test test = new Test();
int result = test.f(20);
System.out.println("result = " + result);
}
}

为什么结果是:result = -2102132736
是一个负数
如果将test.f(20)中的20改为10的话,运算的结果是正数
...全文
149 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
blliy117 2007-09-07
  • 打赏
  • 举报
回复
超出了int的范围了,具体为什么是这个数呢,
是因为求的是int可表示最大数的模
  • 打赏
  • 举报
回复
把程序段中所有的 int 全改为 long,最大可以支持到 20 的阶乘。

想再计算更大的阶乘的话需要使用 BigInteger 类了,BigInteger 可以精确计算任意位数的数值,仅受计算机内存限制。下面是采用 BigInteger 的实现,可以参考一下。

import java.math.BigInteger;

public class Test2 {

  public static BigInteger factor(BigInteger n) {
    if (n.equals(new BigInteger("0"))) {
      return new BigInteger("1");
    }
    return n.multiply(factor(n.subtract(new BigInteger("1"))));
  }
  
  public static void main(String[] args) {
    String s = "200";
    BigInteger big = factor(new BigInteger(s));
    System.out.println(s + "! = " + big.toString());
    System.out.println(s + "! 共有 " + big.toString().length() + " 位");
  }
}
zhangchao0323 2007-09-06
  • 打赏
  • 举报
回复

public class Test
{
public long f(long n)
{
if (n == 0)
{
return 1;
}
return n * f(n - 1);
}

public static void main(String[] args)
{
Test test = new Test();

long result = test.f(20);

System.out.println("result = " + result);
}
}
zephyr_cc 2007-09-06
  • 打赏
  • 举报
回复
超int的范围啦.....
你把result改成long
f()的返回值改成long试试

62,623

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧