求第n位斐波那契数列,n<=5000。
还是大数问题,这次是大数加法。仿照UVa 623的解法来做。623位数可以一位一位的增,但是这个需要预先给够位数,要是按六位存一个数组元素里面的话,300位足够了,粗算一下n=5000大概有1044位,len=300*6足够存下了。就是不知道最后输出答案时我让pos初始为len为什么会WA,这个初始化对结果有影响?
1 #include<iostream> 2 #include<cstdio> 3 #define mod 1000000 4 using namespace std; 5 const int maxn = 5005; 6 const int len = 300; 7 int f[maxn][maxn]; 8 9 int main() 10 { 11 f[0][0] = 0, f[1][0] = 1; 12 for (int i = 2; i <= 5001; i++) 13 { 14 int c = 0; 15 for (int j = 0; j <= len; j++) 16 { 17 int t = f[i - 1][j] + f[i - 2][j]+c; 18 f[i][j] = t%mod; 19 c = t / mod; 20 } 21 } 22 int n; 23 while (scanf("%d",&n)==1) 24 { 25 int pos = 0;//从0开始,从len开始会WA,不太懂 26 for (int i = len; i >= 0; i--) { 27 if (f[n][i] > 0) { 28 pos = i; break; 29 } 30 } 31 printf("The Fibonacci number for %d is ", n); 32 printf("%d", f[n][pos]); 33 for (int i = pos - 1; i >= 0; i--) 34 printf("%06d", f[n][i]); 35 printf("\n"); 36 } 37 return 0; 38 }
Uva 495
好吧,用Python写就几行。。。
1 fib=[0,1] 2 for i in range(5000): 3 fib+=[fib[-2]+fib[-1]] 4 while True: 5 try: 6 n=int(input()) 7 print("The Fibonacci number for {0} is {1}".format(n,fib[n])) 8 except: 9 break
UVa 495 Python
其实Java也不长。。。。
1 import java.math.BigInteger; 2 import java.util.*; 3 class Main{ 4 public static void main(String[] args){ 5 Scanner in =new Scanner (System.in); 6 BigInteger ans[]=new BigInteger[5005]; 7 ans[0]=BigInteger.ZERO; 8 ans[1]=BigInteger.ONE; 9 for(int i=2;i<=5003;i++) 10 ans[i]=ans[i-1].add(ans[i-2]); 11 while(in.hasNext()){ 12 int n=in.nextInt(); 13 System.out.println("The Fibonacci number for "+ n +" is " + ans[n]); 14 } 15 } 16 }
Uva 495 Java
时间: 2024-11-04 11:19:08