您的位置:首页 > 编程语言 > C语言/C++

Java & C++ 大数计算

2016-07-17 09:48 344 查看
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=1; i<=len2-len1; i++)
str1="0"+str1;
} else {
for(int i=1; i<len1-len2; i++) {
str2="0"+str2;
}
}
len1=str1.length();
int cf=0;
int tem;
for(int i=len1-1; i>=0; i--) {
tem=str1[i]-'0'+str2[i]-'0'+cf;
cf=tem/10;
tem%=10;
str=char(tem+'0')+str;
}
if(cf!=0)str=char(cf+'0')+str;
return str;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: