序列
问题描述 :
数列A满足An = An-1 + An-2 + An-3, n >= 3
编写程序,给定A0, A1 和 A2, 计算A99
输入:
输入包含多行数据
每行数据包含3个整数A0, A1, A2 (0 <= A0, A1, A2 <= 32767)
数据以EOF结束
输出:
对于输入的每一行输出A99的值
样例输入:
1 1 1
样例输出:
69087442470169316923566147 代码实现:
//* @author:
import java.util.*;
import java.math.BigInteger;
public class Main {
static String doAdd(String a, String b) { //两个大数相加的方法。
String str = "";
int lenA = a.length();
int lenB = b.length();
int maxLen = (lenA > lenB) ? lenA : lenB;
int minLen = (lenA < lenB) ? lenA : lenB;
String strTmp = "";
for (int i = maxLen - minLen; i > 0; i--) {
strTmp += "0";
}
// 把长度调整到相同
if (maxLen == lenA) {
b = strTmp + b;
} else
a = strTmp + a;
int JW = 0;// 进位
for (int i = maxLen - 1; i >= 0; i--) {
int tempA = Integer.parseInt(String.valueOf(a.charAt(i)));
int tempB = Integer.parseInt(String.valueOf(b.charAt(i)));
int temp;
if (tempA + tempB + JW >= 10 && i != 0) {
temp = tempA + tempB + JW - 10;
JW = 1;
} else {
temp = tempA + tempB + JW;
JW = 0;
}
str = String.valueOf(temp) + str;
}
return str;
}
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
String a[]=new String [100];
while(in.hasNext()){
a[0]=Integer.toString(in.nextInt());
a[1]=Integer.toString(in.nextInt());
a[2]=Integer.toString(in.nextInt());
for(int i=3;i< 100;i++){
String temp=doAdd(a[i-1],a[i-2]);
a[i]=doAdd(temp,a[i-3]);
}
System.out.println(a[99]);
}
}
}
方法二:
import java.math.*;
import java.util.*;
public class Main
{
public static BigInteger calc(BigInteger a,BigInteger b,BigInteger c)
{
BigInteger now = c;
BigInteger last = b;
BigInteger llast = a;
BigInteger answer;
for(int i=0;i< 97;i++) {
answer = now.add(last);
answer = answer.add(llast);
llast = last;
last = now;
now = answer;
}
return now;
}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
while(in.hasNext()) {
int a0 = in.nextInt();
BigInteger A0 = BigInteger.valueOf(a0);
int a1 = in.nextInt();
BigInteger A1 = BigInteger.valueOf(a1);
int a2 = in.nextInt();
BigInteger A2 = BigInteger.valueOf(a2);
System.out.println(calc(A0,A1,A2));
}
}
}