Java & C++ 大数计算

Java--大数计算,妈妈再也不用担心我的学习了 .

BigInteger

英文API:

http://docs.oracle.com/javase/8/docs/api/

中文API:

http://tool.oschina.net/apidocs/apidoc?api=jdk-zh

import java.math.BigInteger;
import java.util.Scanner; //hdu 1002----A + B Problem II public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int i = 1;
while (n-- != 0) {
BigInteger a = new BigInteger(sc.next());
BigInteger b = new BigInteger(sc.next());
System.out.println("Case " + (i++) + ":");
System.out.println(a + " + " + b + " = " + a.add(b));
if (n != 0)
System.out.println();
}
}
}

 

import java.math.BigInteger;
import java.util.Scanner; //hdu 1042 N! public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
BigInteger a = new BigInteger(sc.next()); if (a.compareTo(new BigInteger("0")) == 0) {
// 如果是0 返回1
System.out.println("1");
continue;
} BigInteger sum = a;
// 举例 求 9! 这是 sum=a=9 BigInteger b = new BigInteger("1"); while (a.compareTo(b) != 0) {
// while a不等于1
// 第一次循环sum=9 sum=sum*8(a=a-1)a=8
// 第二次循环 sum=72,sum=sum*7(a=a-1)a=7
// 第三次循环 sum=504,sum=sum*6(a=a-1)a=6
// .....等于1时退出
sum = sum.multiply(a = a.subtract(b));
}
System.out.println(sum);
}
}
}

 -C++

 string add(string str1,string str2)
{
string str;
int len1=str1.length();
int len2=str2.length();
if(len1<len2) {
for(int i=; i<=len2-len1; i++)
str1=""+str1;
} else {
for(int i=; i<len1-len2; i++) {
str2=""+str2;
}
}
len1=str1.length();
int cf=;
int tem;
for(int i=len1-; i>=; i--) {
tem=str1[i]-''+str2[i]-''+cf;
cf=tem/;
tem%=;
str=char(tem+'')+str;
}
if(cf!=)str=char(cf+'')+str;
return str;
}
上一篇:Java并发编程系列之二十八:CompletionService


下一篇:PHP:小数位计算