日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > java >内容正文

java

处理大数必选BigInteger(记洛谷P1009题WA的经历,Java语言描述)

發(fā)布時(shí)間:2025/3/15 java 20 豆豆
生活随笔 收集整理的這篇文章主要介紹了 处理大数必选BigInteger(记洛谷P1009题WA的经历,Java语言描述) 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

題目大意

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)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。