Fibonacci Numbers(斐波那契数列 前四位 后四位)

本文针对HDU 3117题目进行了解析,该题要求输出斐波那契数列中小于8位数的完整数值,对于大于8位的数则输出前四位及后四位。文章提供了C++代码实现,通过矩阵快速幂的方式求解,并特别注意了后四位不足四位时的补零操作。

题意:http://http://acm.hdu.edu.cn/showproblem.php?pid=3117

如果斐波那契数小于8位的就输出这个数,大于8位的就输出前四位,以及后四位

 

求后四位可参考这题hdu 1568 Fibonacci

http://http://blog.youkuaiyun.com/yhyyxt/article/details/45974537

 

唯一要注意的一点就是求后四位时,不足四位要补零,一开始就是忘了补零,wa了

#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <math.h>
using namespace std;
#define mod 1000000000
struct mat
{
	__int64 a[2][2];
};
mat mul(mat a,mat b)
{
	mat ret;
	for(int i=0;i<2;i++)
	{
		for(int j=0;j<2;j++)
		{
			ret.a[i][j] = (a.a[i][0]*b.a[0][j]+a.a[i][1]*b.a[1][j])%mod;
		}
	}
	return ret;
}
mat mpower(mat a,int x)
{
	mat I;
	I.a[0][0] = I.a[1][1] = 1;
	I.a[0][1] = I.a[1][0] = 0;
	while(x)
	{
		if(x&1) I = mul(I,a);
		x>>=1;
		a = mul(a,a);
	}
	return I;
}
int main()
{
	int n;
	while(cin>>n)
	{
		mat tmp;
		tmp.a[0][0] = tmp.a[0][1] = tmp.a[1][0]=1;
		tmp.a[1][1] = 0;
		if(n==0||n==1) 
		{
			cout<<n<<endl;
			continue;
		}
		tmp = mpower(tmp,n-1);
		if(n<=39)
		{
			int sum = tmp.a[0][0];
			cout<<sum<<endl;
		}
		else
		{
			__int64 a1 = tmp.a[0][0];
			double ai = log10((1*1.0)/sqrt(5*1.0));  
        	double bi = n*(log10((1+sqrt(5*1.0))*1.0/2))+ai;  
        	bi = bi-floor(bi);  
        	bi = pow(10,bi);  
        	int a2 = (int)(bi*1000);  
			cout<<a2<<"...";
			int p[4];
			for(int i=0;i<4;i++)
			{
				p[i] = a1%10;
				a1/=10;
			}
			for(int i=3;i>=0;i--) cout<<p[i];
			cout<<endl;
		}
	}
	return 0;
}


 

要编写一个C程序来计算Fibonacci数列并根据用户输入的位数返回相应的值,你可以使用动态内存分配来存储足够大的数值。Fibonacci数列的定义是每个数字(从第三项开始)都是两项之和。 以下是一个简单的示例,它首先询问用户要计算多少位的Fibonacci数,然后逐个生成并打印这些位数: ```c #include <stdio.h> #include <stdlib.h> // Function to calculate the Fibonacci number using dynamic memory long long fibonacci(int n) { if (n <= 0) return 0; else if (n == 1) return 1; // Allocate memory for storing the larger of the two previous numbers char* fib_str = malloc(sizeof(char) * (n + 1)); long long fib_num = 1, prev_num = 0; int i = 2; while (i <= n) { fib_num += prev_num; sprintf(fib_str, "%lld", fib_num); free(fib_str); // Free the old string before creating a new one fib_str = realloc(fib_str, sizeof(char) * (n - i + 1)); // Resize string // Update the previous and current numbers prev_num = fib_num; i++; } return fib_num; } int main() { int bits; printf("Enter the number of bits for the Fibonacci number: "); scanf("%d", &bits); long long result = fibonacci(bits); printf("The %d-bit Fibonacci number is: %lld\n", bits, result); return 0; } ``` 在这个程序中,`fibonacci`函数使用了`malloc`和`realloc`来动态地创建字符串表示数字,以便随着位数的增长而扩展空间。最后,记得用`free`释放之分配的内存。 运行此程序后,它会要求用户输入他们想要的Fibonacci数的位数,并计算出相应值。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值