第一道传送们:NYoj 113 某种序列
一开始迭代顺序弄反了,a2=a3,a1=a2,a0=a1......太无脑了...因为从0开始,100-3,循环计算97次
import java.math.BigInteger;
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while(in.hasNext()) {
BigInteger a0 = in.nextBigInteger();
BigInteger a1 = in.nextBigInteger();
BigInteger a2 = in.nextBigInteger();
BigInteger a3 = BigInteger.ZERO;
for(int i = 1; i<=97; i++) {
a3 = a0.add(a1).add(a2);
a0 = a1;
a1 = a2;
a2 = a3;
}
System.out.println(a2);
}
}
}
用数组套公式做也行:
import java.math.BigInteger;
import java.util.Scanner;
public class Main
{
public static void main(String args[])
{
Scanner cin = new Scanner(System.in);
BigInteger a[] = new BigInteger[100];
while(cin.hasNext())
{
for(int i = 0; i <= 2; ++i)
a[i] = cin.nextBigInteger();
for(int i = 3; i <= 99; ++i)
a[i] = a[i - 1].add(a[i - 2]).add(a[i - 3]);
System.out.println(a[99]);
}
}
}
C/C++版:
也就是把数位存进数组里面,思路迭代和第一中Java一样:
#include <stdio.h>
#include <string.h>
#define MAX 1010
int a[MAX],b[MAX],c[MAX],sum[MAX];
void init(int x,int *a)
{
int i=0;
while(x)
{
a[i++]=x%10;
x/=10;
}
}
int main()
{
int aa,bb,cc;
while(scanf("%d %d %d",&aa,&bb,&cc)!=EOF)
{
int i,j,t;
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
memset(c,0,sizeof(c));
init(aa,a);init(bb,b);init(cc,c);
/*if(aa==0&&bb==0&&cc==0)
{
printf("0\n");
continue;
}*/
//for(i=0;i<10;i++)
//printf("%d %d %d ",a[i],b[i],c[i]);
for(i=3;i<=99;i++)
{
memset(sum,0,sizeof(sum));
for(j=0;j<MAX;j++)
{
sum[j]+=(a[j]+b[j]+c[j]);
if(sum[j]>9)
{
t=sum[j];
sum[j]=t%10;
sum[j+1]=t/10;
}
}
for(j=0;j<MAX;j++)
{
a[j]=b[j];
b[j]=c[j];
c[j]=sum[j];
}
}
for(j=MAX-1;j>0&&sum[j]==0;j--);
for(;j>=0;j--)
printf("%d",sum[j]);
printf("\n");
}
return 0;
}