LeeBlog

导航

HDU 1316 How Many Fibs? 大数

Java

import java.io.*;
import java.util.*;
import java.math.*;

public class aa
{
	public static void main( String[] args )
	{
		BigInteger f[] = new BigInteger[505],a,b;
		f[1] = BigInteger.valueOf(1);
		f[2] = BigInteger.valueOf(2);
		for( int i = 3; i < 505; ++i )
			f[i] = f[i-1].add( f[i-2] );
		Scanner cin = new Scanner(System.in);
		while( cin.hasNextBigInteger() )
		{
			a = cin.nextBigInteger();
			b = cin.nextBigInteger();
			if( a.compareTo(BigInteger.ZERO) == 0 && b.compareTo(BigInteger.ZERO) == 0)
				break;
			int c = 0;
			for( int i = 1; i < 505; ++i )
			{
				if( f[i].compareTo(b) > 0 )
					break;
				if( f[i].compareTo(a) >= 0 && f[i].compareTo(b) <= 0 )
					++c;
			}
			System.out.println( c );
		}
	}
}

这题很明显只能用大数,先把fibs求出来,然后再去找区间

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define max 124
char str1[max],str2[max];
char ch[10000][max] ={0};
void chart( )
{
     int i = 3,len = 0;
     ch[1][0] = '1';
     ch[2][0] = '2';
     for( ; len < max; ++i )
     {
          int j = 0, t = 0;
          while( ch[i - 2][j] )
          {
                 t += ch[i-2][j] - '0' + ch[i-1][j] -'0';
                 ch[i][j] = t % 10 + '0';
                 t /= 10;
                 ++j;
          }
          while( ch[i-1][j] )
          {
                 t += ch[i-1][j] - '0';
                 ch[i][j] = t % 10 + '0';
                 t /= 10;
                 ++j;
                 }
          while( t )
          {
                 ch[i][j] = t % 10 + '0';
                 t /= 10;
                 ++j;
                 }
          len = strlen( ch[i] );
      }
 }
int cmp( char str[],char str2[] )
{
    char str1[max] = {0};//别丢了这一步,否则WA
    strcpy( str1,str );
    int len1 = strlen( str1 ),len2 = strlen( str2 );
    if( len1 > len2 )
        return 1;
    else  if( len1 < len2 )
          return -1;
    else
    {
        for( int p = len1 - 1,q = 0; p > q;--p,++q )
        {
             char c = str1[p];
             str1[p] = str1[q];
             str1[q] = c;
         }
        return strcmp( str1 ,str2 );
    }
}
int cal( )
{
    int sum = 0,i = -1;
    while( cmp(ch[++i],str1) < 0 );
    while( cmp( ch[i],str2 ) <= 0 )
    {
           ++i;
           ++sum;
           }
    return sum;
}
int main( )
{
    chart(  );
    while( scanf( "%s%s",str1,str2 ),str1[0] + str2[0] != '0' + '0' )
           printf( "%d\n",cal(  ) );
    return 0;
}

posted on 2011-04-08 21:21  LeeBlog  阅读(340)  评论(0编辑  收藏  举报