POJ 3982 序列 [解題報告] Java

來源:互聯網
上載者:User

標籤:

序列

問題描述 :

數列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));
}
}
}



POJ 3982 序列 [解題報告] Java

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.