题目详情 求(3 + √5)^n的小数点前(整数部分)的最低3位。 例如:(3 + √5)^5 = 3935.73982…则输出935 而(3 + √5)^2 = 27.4164079.. 则输出027。 输入格式: 多组数据,每组一行包含一个正整数n, 2<=0<=2000000000。 输出格式: 每组数据输出一行,恰好包含3个数字。 答题说明 输入样例 2 5 输出样例: 027 935 思路: 您应该知道(3 - √5 ) ^ n为一个大于0小于1的数,是吧?如何将它运用到这道题呢? 通过一定的推断,我们 知道了an = (3 + √5)^ n + (3 - √5 ) ^ n为一个整数, 如果我们求出an了,那么(3 + √5)^ n的整数部分就是 an - 1了,对吧? 接着通过几次构造的尝试,我们会得到递推公式:an * ( 3 + √5 + 3 - √5) = a(n+1) + 4*a(n-1), 即6*an = a(n+1) + 4*a(n-1), 也即a(n+1) = 6*an - 4*a(n-1), 这样就可以通过构造矩阵来快速求了, 详见代码。 代码: #include <iostream> #include <climits> #include <cmath> #include <algorithm> #include <iomanip> #define inf 0x7fffffff #define MOD 1000000007 using namespace std; void mul(int lhs[2][2], int rhs[2][2]) { int res[2][2] = {0, 0, 0, 0}; int i, j, k; for(i=0; i!=2; i++) { for(j=0; j!=2; j++) { for(k=0; k!=2; k++) res[i][j] += (lhs[i][k]%1000) * (rhs[k][j]%1000); res[i][j] %= 1000; } } copy(&res[0][0], &res[1][1], &lhs[0][0]); } unsigned int n; int main() { while(cin>>n) { int res[2][2] = {6, 2, 0, 0}; int matrix[2][2] = {6, 1, -4, 0}; n--; while(n!=0) { if(n&1) { mul(res, matrix); } mul(matrix, matrix); n >>= 1; } cout<<setw(3)<<setfill('0')<<(res[0][0] + 1000 - 1) % 1000<<endl; } return 0; }