如何解决如何将 java long 类型变量的数组更改为 java BigInteger 类以支持非常大的输出?
我正在尝试更新 Java 程序以支持非常大的输出。目前程序支持长型数据,我想把长型改成BigInteger类。
这是原来的程序,
class WaysDP_long
{
static int A = 3;
static int B = 2;
static int C = 2;
static long CountWays(int a,int b,int c,long [][][]dp)
{
if (a > A || c >= C) return 0L;
if (b >= B) return 1L;
if (dp[a][b][c] != -1) return dp[a][b][c];
long ways = 0;
ways += CountWays(a+1,b,c+1,dp);
ways += CountWays(a+1,b+1,c,b+2,b+4,dp);
// Memorize and return
return dp[a][b][c] = ways;
}
// Driver code
public static void main(String[] args)
{
long[][][] dp = new long[A+1][B+5][C];
for(int i = 0; i < A+1; i++)
for(int j = 0; j < B+5; j++)
for(int k = 0; k < C; k++) dp[i][j][k]=-1L;
System.out.println(CountWays(0,dp));
}
}
为了支持更大的 A、B 和 C 值,我试图将一些变量转换为 BigInteger, 这是我更新的代码,
class WaysDP_Large
{
static int A = 3;
static int B = 2;
static int C = 2;
static boolean[][][] supportDP = new boolean[B+1][A+5][C]; // to avoid BigInteger negative initialization.
static BigInteger CountWays(int a,BigInteger [][][]dp)
{
if (a > B || c >= C) return BigInteger.ZERO;
if (b >= A) return BigInteger.ONE;
if (supportDP[a][b][c]) return dp[a][b][c];
BigInteger ways = BigInteger.ZERO;
ways.add(CountWays(a+1,dp));
ways.add(CountWays(a+1,dp));
// Memorize and return
supportDP[a][b][c] = true;
//dp[ballsPlayed][currentscore][wicketsGone] = new BigInteger();
return dp[a][b][c] = ways;
}
// Driver code
public static void main(String[] args)
{
BigInteger[][][] dp = new BigInteger[B+1][A+5][C];
for(int i = 0; i < B+1; i++)
for(int j = 0; j < A+5; j++)
for(int k = 0; k < C; k++) supportDP[i][j][k] = false;
// for(int i = 0; i < balls+1; i++)
// for(int j = 0; j < target+5; j++)
// for(int k = 0; k < wickets; k++) dp[i][j][k] = BigInteger.ZERO;
System.out.println(CountWays(0,dp));
}
}
但更新后的代码总是给出输出 0,它应该给出 13。 [对于 3、4、3,它将是 20]
可能是 BigInteger 赋值和添加的问题。任何克服问题的提示将不胜感激。谢谢。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。