UVA 10236 - The Fibonacci Primes(斐波那契素数)

The Fibonacci number sequence is 1, 1, 2, 3, 5, 8, 13 and so on. You can see that except the first two
numbers the others are summation of their previous two numbers. A Fibonacci Prime is a Fibonacci
number which is relatively prime to all the smaller Fibonacci numbers. First such Fibonacci Prime is
2, the second one is 3, the third one is 5, the fourth one is 13 and so on. Given the serial of a Fibonacci
Prime you will have to print the first nine digits of it. If the number has less than nine digits then print
all the digits.
Input
The input file contains several lines of input. Each line contains an integer N (0 < N ≤ 22000) which
indicates the serial of a Fibonacci Prime. Input is terminated by End of File.
Output
For each line of input produce one line of output which contains at most nine digits according to the
problem statement.
Sample Input
1
2
3
Sample Output
2
3
5

题意:给出一个数n,求出第n个素斐波那契数

思路:
定理:若n为素数则f(n)为素数
所以先打素数表,第n个素斐波那契数就是第n个素数的斐波那契数,预处理斐波那契数(注意保留位数)然后查下标。

AC代码:

#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
const int N =250010;//注意这里题目给的是220000,但数据比这个大(坑)
bool prime[N];
double f[N];
int p[N], tot;
void su()
{
    
    
    for(int i = 2; i < N; i ++)
        prime[i] = true;
    for(int i = 2; i < N; i++)
    {
    
    
        if(prime[i]) p[tot ++] = i;
        for(int j = 0; j < tot && i * p[j] < N; j++){
    
    
            prime[i * p[j]] = false;
            if(i % p[j] == 0) break;
        }
    }
}
void init(int n)
{
    
    
	int flag = 0;
	f[1] = f[2] = 1;
	for (int i = 3; i < n; i++)
    {
    
    
		if (flag)
        f[i]=f[i-1]+ f[i - 2] / 10;
		else
		f[i]=f[i-1]+ f[i - 2];
		flag=0;
		while(f[i]>=1000000000)
        {
    
    
			flag = 1;
			f[i]/= 10;
		}
	}
}
int main()
{
    
    
    int n;
    su();
    init(N);
    //for(int i=1;i<=10;i++)cout<<p[i]<<" "<<f[i]<<endl;
    while(scanf("%d",&n)!=EOF)
    {
    
    
        if(n==1)
        {
    
    
            printf("2\n");
            continue;
        }
        if(n==2)
        {
    
    
            printf("3\n");
            continue;
        }
        printf("%d\n",(int)f[p[n-1]]);
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43244265/article/details/104395722