200以内正数的阶乘(BigInteger)

题目:计算200以内正数的阶乘;

考虑使用 int 可能会超出范围,这里使用BigInteger
导包:java.math.BigInteger
方法:
int转BigInteger, int自动向上转为long,然后用valueOf转为BIgInteger;
在这里插入图片描述
乘:
在这里插入图片描述

思路:动态规划

方法一:从下往上dp

import java.io.*;
import java.math.BigInteger;
public class Main{
    public static void main(String[] args) throws IOException{
        BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
        String s=in.readLine();
        int n=Integer.parseInt(s);
        BigInteger[] dp=new BigInteger[n+1];
        dp[0]=BigInteger.valueOf(1);
        dp[1]=BigInteger.valueOf(1);
        for(int i=1;i<=n;i++){
            dp[i]=BigInteger.valueOf(i).multiply(dp[i-1]);
        }
        System.out.println(dp[n]);
        
    }
}

方法二:递归的动态规划

import java.util.Scanner;
import  java.util.Arrays;
import java.math.BigInteger;
 
public class Main {
public static BigInteger memo[];
       public static void main(String[] args){
        Scanner in=new Scanner(System.in);
        int n=in.nextInt();
        memo=new BigInteger[n+1];
        //Arrays.fill(memo,-1);
 
        BigInteger r=dp(n);
        System.out.println(r);
    }
 
    static BigInteger dp(int n){
        if(n<1){
            return BigInteger.valueOf(1);
        }
        //base case
        memo[1]=BigInteger.valueOf(1);
 
        // 重叠子问题
        memo[n]=BigInteger.valueOf(n).multiply(dp(n-1));
        return memo[n];
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值