处理大数必选BigInteger(记洛谷P1009题WA的经历,Java语言描述)
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                处理大数必选BigInteger(记洛谷P1009题WA的经历,Java语言描述)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.                        
                                題目大意
P1009題目鏈接
 
分析
題目很簡單,但是這是階乘啊,更何況是階乘和,long都不夠,用int純屬作死……
Java并無C的longlong,但我們有java.math.BigInteger啊,應該是超大的,很強很強!
思路就是內部用循環寫求每次的階乘,當然求解過程可優化~~
第一次提交——WA
import java.util.Scanner;public class Main {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);int limit = scanner.nextInt();int sum = 0;for (int i = 1; i <= limit; i++) {int temp = 1;for (int j = 1; j <= i; j++) {temp *= j;}sum += temp;}System.out.println(sum);scanner.close();} }我竟然敢用int,膽子不小啊!!
第二次提交——WA
對long的卑微理解的不深刻,想試一下,就交了個long(其實最愚蠢的是階乘和用的long但階乘沒用,tcl……)
import java.util.Scanner;public class Main {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);int limit = scanner.nextInt();long sum = 0;for (int i = 1; i <= limit; i++) {int temp = 1;for (int j = 1; j <= i; j++) {temp *= j;}sum += temp;}System.out.println(sum);scanner.close();} }既然錯了,就知道long不行了,自測一下:
 
確實,鐵打的溢出,那就用更大的——BigInteger大神~~
第三次提交——AC
import java.math.BigInteger; import java.util.Scanner;public class Main {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);int limit = scanner.nextInt();BigInteger sum = new BigInteger("0");for (int i = 1; i <= limit; i++) {BigInteger temp = new BigInteger("1");for (Integer j = 1; j <= i; j++) {temp = temp.multiply(new BigInteger(j.toString()));}sum = sum.add(temp);}System.out.println(sum.toString());scanner.close();} }對這玩意,你的+=那些都不好使,必須用內置的函數(方法)去做……
 開始的時候我忘了寫 sum = sum.add(temp); ,寫的是 sum.add(temp); 這樣子的,最后整了一個0,tcl……自測后修復,再測50:
 
 顯然這時long必爆~~而BigInteger就可以AC!!
 
優化
這個題對于階乘的求解每一次都現算,很lj,其實可以把前一次的結果保留下來,乘以下一個數,即是下一次階乘咯,好玩吧hh……
BigInteger
API文檔
 注意構造器,這個破東西不好構造,我們做OJ或者簡單使用的時候用String做構造器即可,所以我為了toString方便,直接用的Integer當循環變量類型——直接包裝,嘿嘿~~
總結
以上是生活随笔為你收集整理的处理大数必选BigInteger(记洛谷P1009题WA的经历,Java语言描述)的全部內容,希望文章能夠幫你解決所遇到的問題。
                            
                        - 上一篇: 筹款の不定方程(洛谷P4956题题解,J
 - 下一篇: contains()+replaceFi