Java大整數運算之計算1!+2!+…+100!的總和.
阿新 • • 發佈:2019-01-03
最近開了Java課程,可是課後習題似乎有點超前了一點點,莫非老師要鍛鍊我們的動手能力………………..
Java大整數運算轉載
import java.util.*;
import java.math.*;
public class Main{
public static void main(String args[]){
Scanner cin = new Scanner(System.in);
BigInteger a, b;
//以檔案EOF結束
while (cin.hasNext()){
a = cin.nextBigInteger();
b = cin.nextBigInteger();
System.out .println(a.add(b)); //大整數加法
System.out.println(a.subtract(b)); //大整數減法
System.out.println(a.multiply(b)); //大整數乘法
System.out.println(a.divide(b)); //大整數除法(取整)
System.out.println(a.remainder(b)); //大整數取模
//大整數的比較
if( a.compareTo(b) == 0 ) System.out .println("a == b");
//大整數a==b
else if( a.compareTo(b) > 0 ) System.out.println("a > b");
//大整數a>b
else if( a.compareTo(b) < 0 ) System.out.println("a < b");
//大整數a<b
//大整數絕對值
System.out.println(a.abs()); //大整數a的絕對值
//大整數的冪
int exponent=10;
System.out.println(a.pow(exponent)); //大整數a的exponent次冪
//返回大整數十進位制的字串表示
System.out.println(a.toString());
//返回大整數p進位制的字串表示
int p=8;
System.out.println(a.toString(p));
}
}
}
大整數應用——計算1!+2!+…+100!的總和.
import java.util.Scanner;
import java.math.*;
public class four {
public static void main(String[] args) {
// TODO 自動生成的方法存根
System.out.println("input the n:");
Scanner sc=new Scanner(System.in);
int a=sc.nextInt();
BigInteger sum=new BigInteger("0");
BigInteger O=new BigInteger("0"); //大寫字母O
BigInteger D=new BigInteger("1");
for(int i=1;i<=a;i++){
BigInteger b=new BigInteger("1");
String I=i+"";
BigInteger c=new BigInteger(I);
do {
b=c.multiply(b);
c=c.subtract(D);
} while (!(c.equals(O))); //這是大寫字母O
sum=sum.add(b);
}
System.out.println("\n1!+2!+3!+......+100!= "+sum);
}
}
執行截圖
小結
這次的Java大整數的應用是十分的精彩的,Java帶給了我們太多太多的便利了,要是擱在C裡面,估計只能一行行的碼了,理解面對物件,記住大整數的物件是字串即可。