处理大数必选BigInteger(记洛谷P1009题WA的经历,Java语言描述)
題目大意
P1009題目鏈接
分析
題目很簡(jiǎn)單,但是這是階乘啊,更何況是階乘和,long都不夠,用int純屬作死……
Java并無C的longlong,但我們有java.math.BigInteger啊,應(yīng)該是超大的,很強(qiáng)很強(qiáng)!
思路就是內(nèi)部用循環(huán)寫求每次的階乘,當(dāng)然求解過程可優(yōu)化~~
第一次提交——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
對(duì)long的卑微理解的不深刻,想試一下,就交了個(gè)long(其實(shí)最愚蠢的是階乘和用的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();} }既然錯(cuò)了,就知道long不行了,自測(cè)一下:
確實(shí),鐵打的溢出,那就用更大的——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();} }對(duì)這玩意,你的+=那些都不好使,必須用內(nèi)置的函數(shù)(方法)去做……
開始的時(shí)候我忘了寫 sum = sum.add(temp); ,寫的是 sum.add(temp); 這樣子的,最后整了一個(gè)0,tcl……自測(cè)后修復(fù),再測(cè)50:
顯然這時(shí)long必爆~~而BigInteger就可以AC!!
優(yōu)化
這個(gè)題對(duì)于階乘的求解每一次都現(xiàn)算,很lj,其實(shí)可以把前一次的結(jié)果保留下來,乘以下一個(gè)數(shù),即是下一次階乘咯,好玩吧hh……
BigInteger
API文檔
注意構(gòu)造器,這個(gè)破東西不好構(gòu)造,我們做OJ或者簡(jiǎn)單使用的時(shí)候用String做構(gòu)造器即可,所以我為了toString方便,直接用的Integer當(dāng)循環(huán)變量類型——直接包裝,嘿嘿~~
總結(jié)
以上是生活随笔為你收集整理的处理大数必选BigInteger(记洛谷P1009题WA的经历,Java语言描述)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 筹款の不定方程(洛谷P4956题题解,J
- 下一篇: contains()+replaceFi