算法题:斐波那契再搞事情(Python解法)
题目
解题
这是一道填空题
难点有两个:计算和化简
巧的是
Python有可以化简分数的库函数Fraction
>>> Fraction(10, -8)
Fraction(-5, 4)
>>> Fraction(Fraction(1, 7), 5)
Fraction(1, 35)
>>> Fraction(Fraction(1, 7), Fraction(2, 3))
Fraction(3, 14)
>>> Fraction('314')
Fraction(314, 1)
>>> Fraction('-35/4')
Fraction(-35, 4)
>>> Fraction('3.1415') # conversion from numeric string
Fraction(6283, 2000)
>>> Fraction('-47e-2') # string may include a decimal exponent
Fraction(-47, 100)
>>> Fraction(1.47) # direct construction from float (exact conversion)
Fraction(6620291452234629, 4503599627370496)
>>> Fraction(2.25)
Fraction(9, 4)
>>> Fraction(Decimal('1.47'))
Fraction(147, 100)
所以问题就可以迎刃而解
from fractions import Fraction
n = int(input())
l=[]
ls=[]
sum=0
F1, F2 = 1, 1
l.append(F1)
l.append(F2)
for i in range(3, n + 1):
F1, F2 = F2 % 10007, (F1 + F2) % 10007
l.append(F2)
print(l)
for i in range(n-1):
f=Fraction(1,l[i]*l[i+1])
sum+=f
print(sum)
求13项的值我们需要14项斐波那契数列
官方也给出了C++解法
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
typedef __int128 lll;
lll fibo[20],mother[20],son[20];
void print(lll x){
if(x<0){
putchar('-');
x=-x;
}
if(x>9) print(x/10);
putchar(x%10+'0');
}
int main(){
fibo[1]=fibo[2]=1;
for(int i=3;i<=15;i++) fibo[i]=fibo[i-1]+fibo[i-2];
for(int i=1;i<=13;i++) mother[i]=fibo[i]*fibo[i+1];
lll common=1;
for(int i=1;i<=13;i++){
common*=mother[i];
son[i]=1;
}
for(int i=1;i<=13;i++){
lll cur=common/mother[i];
son[i]*=cur;
}
lll ans=0;
for(int i=1;i<=13;i++) ans+=son[i];
lll g=__gcd(common,ans);
common/=g;ans/=g;
print(ans);
cout<<"/";
print(common);
return 0;
本文来自博客园,作者:{Zeker62},转载请注明原文链接:https://www.cnblogs.com/Zeker62/p/15046262.html