簡體   English   中英

Java程序,用於計算拋出nCr的算術異常“除以零”

[英]Java Program to compute nCr throwing Arithmetic Exception “Divide by zero”

以下代碼嘗試為給定n的各個值計算nCr值,此處r從0到n變化。

輸入采用以下格式:-

輸入格式

第一行包含測試用例T的數量。T行緊隨其后,每個包含整數n。

約束條件

 1<=T<=200 
 1<=n< 1000

輸出格式

對於每個n輸出,nC0到nCn的列表各由一個新行中的單個空格分隔。 如果數字很大,請僅打印最后9位數字。 即取模10 ^ 9

因此,樣本輸入采用以下格式:-

 3
 2
 4
 5

並且示例輸出具有以下格式:-

 1 2 1
 1 4 6 4 1
 1 5 10 10 5 1    

這是代碼

 import java.io.*;
 import java.util.*;
 import java.math.*;

public class Solution {

  public static void main(String[] args) {
      /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */

    Scanner scan = new Scanner(System.in);
    int n = scan.nextInt();
    int j = 0;

    for(int i = 0; i < n; i++){
        int a = scan.nextInt();
        j = 0;
        while(j <= a){
              if( j == 0 || j == a){
                  System.out.print(1 + " ");
              }
              else if( j == 1 || j == (a - 1)){
                  System.out.print(a + " ");
              }else{
                  BigInteger  a1 = (Num(a,j));
                  BigInteger b1 = BigInteger.valueOf(fact(j));
                  BigInteger c1 = a1.divide(b1);
                  BigInteger x1 = BigInteger.valueOf(1000000000);
                  System.out.print( c1.mod(x1)  +" ");
              } 
            j++;
        }
        System.out.println();

    }
}

public static BigInteger Num(int a, int j){
    BigInteger prod = BigInteger.valueOf(1);
    for(int k = 0; k < j; k++){
        int z = a - k;
        BigInteger b = BigInteger.valueOf(z);
        prod = prod.multiply(b);
    }
    return prod;
}

public static long fact(long j){
    long prod = 1;
    for(long i = j; i > 0; i--){
       prod *= i; 
    }
    return prod;
 }
}

它清除了一些測試用例,但在許多情況下都失敗了。 說運行時錯誤,當我在1 999的輸入上對其進行測試時,引發了算術異常“除以零”。

這是異常日志:

      Exception in thread "main" java.lang.ArithmeticException: BigInteger divide by zero
        at java.math.MutableBigInteger.divideKnuth(MutableBigInteger.java:1179)
        at java.math.BigInteger.divideKnuth(BigInteger.java:2049)
        at java.math.BigInteger.divide(BigInteger.java:2030)
        at Solution.main(Solution.java:25)

需要做什么來解決這個問題?

您必須使用BigInteger來計算多達1000個左右的階乘。

public static BigInteger fact(long j){
  BigInteger prod = BigInteger.ONE;
  for(long i = j; i > 0; i--){
    BigInteger f = BigInteger.valueOf( i );
    prod = prod.multiply( f ); 
  }
  return prod;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM