ZOJ 1864 A very easy task (求自然数幂的和)java大数

本文介绍了一种使用递归和记忆化技术求解特定数学问题的方法,通过递推公式进行高效计算,并利用Java的大数处理能力实现。文章详细解释了递归公式的推导过程,以及如何通过记忆化避免重复计算,提高算法效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接:哆啦A梦传送门

题意:求  {\color{Blue} \sum_{i=1}^{n}i^{k}}

题解:

参考神犇博客:神犇

递推求法,由于

     

     那么对于所有的累加得到

     进一步得到

 

     可以看出这是一个递推式,如果我们记

     那么得到如下递归式

      

     递归出口是

 

     

      

 

     为了提高效率,在递归的时候需要记忆化。由于要用到大数,用Java实现。

 

import java.math.*;
import java.util.*;
 
public class Main {
	
	public static final int N = 105;
	public static final BigInteger FLAG = (BigInteger.ZERO).subtract(BigInteger.ONE);
	public static BigInteger[][] C = new BigInteger[N][N];
	public static BigInteger[] ans = new BigInteger[N];
	
	public static void Init(){
		for(int i=0; i<N; i++){
			C[i][0] = C[i][i] = BigInteger.ONE;
			if(i == 0) continue;
			for(int j=1; j<i; j++)
				C[i][j] = C[i-1][j].add(C[i-1][j-1]);
		}
	}
	
	public static BigInteger Solve(BigInteger n, int k){
		if(ans[k].compareTo(FLAG) != 0){
			return ans[k];
		}
		if(k == 1){
			ans[k] = ((n.add(BigInteger.ONE)).multiply(n)).divide(BigInteger.valueOf(2));
			return ans[k];
		}
		BigInteger tmp = BigInteger.ONE;
		for(int i=0; i<k+1; i++){
			tmp = tmp.multiply(n.add(BigInteger.ONE));
		}
		tmp = tmp.subtract(n.add(BigInteger.ONE));
		BigInteger sum = BigInteger.ZERO;
		for(int i=1; i<k; i++){
			BigInteger t = C[k+1][i+1].multiply(Solve(n, k-i));
			sum = sum.add(t);
		}
		ans[k] = (tmp.subtract(sum)).divide(BigInteger.valueOf(k+1));
		return ans[k];
	}
	
	public static void main(String[] args){
		Init();
		Scanner cin = new Scanner(System.in);
		while(cin.hasNext()){
			BigInteger n = cin.nextBigInteger();
			int k = cin.nextInt();
			for(int i=0; i<N; i++){
				ans[i] = FLAG;
			}
			System.out.println(Solve(n, k));
		}
	}
}

 


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值