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

本文介绍了一个算法问题,即求解斐波那契数列中的第N个素数,并提供了一种高效的实现方法。通过预先计算素数表和斐波那契数列,该方法能在限定时间内准确输出所求数的前九位数字。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Problem A
The Fibonacci Primes

Input: standard input
Output: standard output
Time Limit: 8 seconds
Memory Limit: 32 MB

 

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个素数。

思路:先素数打表,然后斐波那契数列的f[i],有个定理,i为素数,f(i)为素数。然后题目要保留前9位,可以用double型来处理。

代码:

#include <stdio.h>
#include <string.h>
const int N = 2500010;

int n, prime[N / 10];
bool isprime[N];
double fib[N];

void Is_Prime() {
	memset(isprime, 0, sizeof(isprime));
	for (int i = 2; i <= 500; i ++) {
		for (int j = i * i; j <= 250000; j += i) {
			isprime[j] = true;
		}
	}
	int num = 1;
	for (int k = 2; k <= 250000; k ++) {
		if (!isprime[k])
			prime[num ++] = k;
	}
	prime[1] = 3; prime[2] = 4;
}

void init() {
	Is_Prime();
	memset(fib, 0, sizeof(fib));
	fib[0] = fib[1] = 1; int bo =0;
	for (int i = 2; i <= 250000; i ++) {
		if (bo) {
			fib[i] = fib[i - 1] + fib[i - 2] / 10; 
			bo = 0;
		}
		else {
			fib[i] = fib[i - 1] + fib[i - 2]; 
		}
		if (fib[i] > 1e9) {
			fib[i] /= 10;
			bo = 1;
		}
	}
}

int main() {
	init();
	while (~scanf("%d", &n)) {
		printf("%d\n", (int)fib[prime[n] - 1]);
	}
	return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值