2017-03-05 8 views
1

プロジェクトオイラーの問題を解決するための基本的なコードがいくつかあります(数字は48です)。技術的には答えが出ますが、答えをきちんと提示するためには、最後のTEN桁をコンソールに表示し、他のすべてを省略したいと思います。BigIntegerの最後の10桁を印刷

私は基本的なデータ型でモジュロ演算子を使用することを示唆していますが、残りの部分を返すことがなぜ解決しないのか分かりませんが、とにかく試してみました。

System.out.println(GrandTotal.mod(BigInteger.TEN)); 

Gets last digit of a number

輸入がjava.math.BigInteger。

public class eulerNo48 { 

    public static void main(String[] args) 
    { 

     /** 
     * Loop that calculates the each number from 1 to 1000 to the 
     * power of itself and sums the results. 
     */ 

     BigInteger sum = BigInteger.ZERO; 
     BigInteger tempVar = BigInteger.ONE; 
     BigInteger GrandTotal = BigInteger.ZERO; 

     for (int i = 1; i <= 1000; i++) { 
      sum = tempVar.pow(i); // Calculates the value of tempVar(1 - 1000) to its respective power (i). 
      tempVar = tempVar.add(BigInteger.ONE); // Increments temVar for each iteration of the loop. 
      GrandTotal = GrandTotal.add(sum); // Adds sum to the grand total. 
     } 


     System.out.println(GrandTotal); 


    } 

} 

すべての援助がありがとうございます。

答えて

0

文字列への変換とを伴って含むが役立つかもしれない働い -

String digits = bigInteger.toString(); // replace bigInteger with GrandTotal in your case 
int numberLength = digits.length(); 
for(int i = numberLength ; i > numberLength - 10; i--) { 
    int digit = digits.charAt(i-1) - '0'; 
    System.out.print(digit); 
} 
+1

は唯一の問題は、最終結果が逆転するということで、これはうまく機能、ありがとうございます。最後の10桁は9110846700です。あなたのコードを自分自身に追加した後、私は0076480119を取得します。逆の方法を考える必要があり、これは完全に機能します。 – shockemc

+0

@shockemc 'i = numberLength-10; i nullpointer

関連する問題