hdu 3117 Fibonacci Numbers

Fibonacci number Fibonacci number In mathematics, the Fibonacci numbers form a sequence defined by the following recurrence relation: 立即下载

Fibonacci Numbers

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1766    Accepted Submission(s): 695


Problem Description
The Fibonacci sequence is the sequence of numbers such that every element is equal to the sum of the two previous elements, except for the first two elements f0 and f1 which are respectively zero and one.

What is the numerical value of the nth Fibonacci number?
 

Input
For each test case, a line will contain an integer i between 0 and 108 inclusively, for which you must compute the ith Fibonacci number fi. Fibonacci numbers get large pretty quickly, so whenever the answer has more than 8 digits, output only the first and last 4 digits of the answer, separating the two parts with an ellipsis (“...”). 

There is no special way to denote the end of the of the input, simply stop when the standard input terminates (after the EOF).
 

Sample Input
0 1 2 3 4 5 35 36 37 38 39 40 64 65
 

Sample Output
0 1 1 2 3 5 9227465 14930352 24157817 39088169 63245986 1023...4155 1061...7723 1716...7565
 

题解及代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#define s_5 sqrt(5.0)
#define sl_5 (0.5+sqrt(5.0)/2.0)
#define sr_5 (0.5-sqrt(5.0)/2.0)
using namespace std;
int fibo[50];
void init()
{
    fibo[0]=0;
    fibo[1]=1;
    int i;
    for(i=2;i<=50;i++)
    {
       fibo[i]=fibo[i-1]+fibo[i-2];
       if(fibo[i]>=100000000)
       {
          break;
       }
    }
}

struct mat
{
    long long  t[2][2];
    void set()
    {
        memset(t,0,sizeof(t));
    }
}a,b;

mat multiple(mat a,mat b,int n,int p)
{
    int i,j,k;
    mat temp;
    temp.set();
    for(i=0;i<n;i++)
    for(j=0;j<n;j++)
    {
        if(a.t[i][j])
        for(k=0;k<n;k++)
            temp.t[i][k]=(temp.t[i][k]+a.t[i][j]*b.t[j][k])%p;
    }
    return temp;
}

mat quick_mod(mat b,int n,int p)
{
    mat t;
    t.t[0][0]=1;
    t.t[0][1]=0;
    t.t[1][0]=0;
    t.t[1][1]=1;
    while(n)
    {
        if(n&1)
        {
           t=multiple(t,b,2,p);
        }
        n>>=1;
        b=multiple(b,b,2,p);
    }
    return t;
}
void init1()
{
    b.t[0][0]=1;
    b.t[0][1]=1;
    b.t[1][0]=1;
    b.t[1][1]=0;
}


int main()
{
    int n;
    init();
    while(cin>>n)
    {
      if(n<40)
      {
          cout<<fibo[n]<<endl;
          continue;
      }
      double s=log10(1.0/s_5)+n*log10(sl_5);
      int len=(int)s+1;
      double t=s-len+4;
      cout<<(int)pow(10.0,t);

      init1();
      a=quick_mod(b,n,10000);
      printf("...%04d\n",a.t[1][0]);
    }
    return 0;
}
/*
一道比较简单的数学题,输出斐波那契数的前四位和后四位。
对于前40项,直接打表输出就可以了。
接下来我们讲一下大于40位的时候如何计算:

对于后四位,我们可以想到,我们进行滚动数组取余就能求得答案,
但是数据量有点大,这样可定会超时,所以只能使用矩阵快速幂来加速。

对于前四位,我们要使用到斐波那契数的封闭公式:
f[n]=1/sqrt(5)*{[0.5+sqrt(5)/2]^n-[0.5-sqrt(5)/2]^n};
由于n很大时,[0.5-sqrt(5)/2]^n很小,几乎可以忽略,又因为我们计算
的是前四位,所以不必管后面的精度,所以这一项可以省略。
f[n]=1/sqrt(5)*[0.5+sqrt(5)/2]^n;
我们假定t=f[n],k为其前四位,想要求t的前四位数k,我们可以使用科学
计数法来写一下t,t=k.xxxx……*10^(len-4);这里len指的是t的位数。
而计算一个数的位数可以使用log10(t)+1来计算得到。

那么知道了这些就很好计算了:首先我们先求出t的位数
len=log10(1/sqrt(5)*[0.5+sqrt(5)/2]^n);
化简一下:len=log10(1/sqrt(5))+n*log10(0.5+sqrt(5)/2);

对于t=k.xxxx……*10^(len-4);我们两边进行log10取对数,
得到log10(t)=log10(k.xxxx……)+len-4;
化简一下得到log10(k.xxxx……)=log10(t)-(len-4);
那么我们为了得到k.xxx……,我们可以求10^[log10(t)-(len-4)]就行了,
最后一项,对k取整。

*转载请注明出处,谢谢。
*/





戴尔G3/AWCC用户必看:揪出WMI Provider Host疯狂占用的元凶,附5.4.35旧版回退保姆级教程 本文针对戴尔G3/AWCC用户遇到的WMI Provider Host异常占用问题,提供了详细的诊断方法和解决方案。通过分析AWCC 5.5.14.0版本的资源占用问题,指导用户回退到稳定版AWCC 5.4.35,并附上保姆级教程和预防措施,帮助用户彻底解决系统卡顿问题。 阅读详情

相关推荐

OC5021B 100V宽电压输入 LED车灯/大功率照明 DC降压型恒流驱动器

适用于LED大功率汽车大灯/大功率照明 OC5021B 100V宽电压输入 5A电流设计 DC-DC降压型恒流驱动IC

Handsome63841990的博客 2427

Fibonacci numbers

Program for Fibonacci numbers The Fibonacci numbers are the numbers in the following integer sequence. 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 141, …….. In mathematical terms, the sequence

screaming的博客 1343

伺服电机三环控制实战:从参数整定到系统优化

本文以实战视角,深入解析伺服电机三环控制(位置环、速度环、电流环)的参数整定与系统优化全流程。文章摒弃复杂理论,通过生动的比喻和分步调试指南,详细阐述了从电流环快速响应、速度环平滑调节到位置环精准定位的调试方法,并提供了常见问题排查与进阶优化技巧,帮助工程师有效提升伺服系统性能与稳定性。

weixin_29201933的博客 252

hdu3117 Fibonacci Numbers

<br /> <br />Fibonacci Numbers<br />Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)<br />Total Submission(s): 328 Accepted Submission(s): 156<br />Problem Description<br />The Fibonacci sequence is the sequence of numbers s

bool_isprime的专栏 1773

Oracle Scheduler任务故障诊断 实战指南

当基础环境无异常时,需聚焦任务本身的配置与状态。定义(JOB)→ 调度(SCHEDULE)→ 执行(SLAVE进程)→ 日志(LOG),每个环节都可能存在卡点。Oracle Scheduler任务的“隐性故障”看似棘手,实则是环境配置、资源竞争、时间逻辑等问题的集中体现。通过本文的诊断工具和排查思路,你可以构建从“基础环境→任务配置→执行链路→日志追踪”的全维度分析体系,让每一个“消失”的任务都无所遁形。

Nuzbb的博客 1077

别再怕DRIVER_VERIFIER_DMA_VIOLATION蓝屏:手把手教你用WinDbg分析IOMMU与驱动冲突

本文深入解析DRIVER_VERIFIER_DMA_VIOLATION蓝屏错误,从IOMMU原理到实战排错,手把手教你使用WinDbg分析驱动冲突。通过理解DMA与IOMMU的核心机制、搭建分析环境、解读DMAR表与设备拓扑,最终定位问题驱动并提供解决方案,帮助开发者和IT运维人员有效应对此类系统崩溃问题。

weixin_30298497的博客 809

[Contest1351]Fibonacci

题面 Description 【问题描述】 豆豆最近迷上了Fibonacci数,然后他开始研究Fibonacci数的乘积。现在他想问你某个数能不能分解成两个Fibonacci数的乘积? Fibonacci数的定义:F0=0,F1=1,Fk=Fk-1+Fk-2。 【输入格式】 第一行一个整数T代表提问次数。 接下来T行,每行一个数字A表示豆豆询问你的数。 【...

asd13716936122的博客 146

秦时明月6.2魔改版_从零到一部署指南_含安卓客户端配置与GM后台直通

本文提供《秦时明月》6.2魔改版从零开始的完整部署指南。详细讲解CentOS服务器环境准备、服务端文件部署与安装、关键端口开放及进程验证。重点涵盖安卓客户端APK的IP修改与重签名方法,并介绍了GM后台工具的访问与使用,助你快速搭建并管理专属游戏服务器。

garlic的博客 323

Fibonacci Numbers

阅读TAOCP中Fibonacci Numbers内容后的想法。 Fibonacci Numbers,形如以下的数列  0,1,1,2,3,5,8,13,21,34, … ,  在这个数列中从第三项开始,每一个元素都是前两个元素的和。  可以写成以下形式:  formula1: F0 = 0; F1 = 1; Fn+2 = Fn+1 + Fn , n>=0.  由此我们就可以得到递归

木木的笔记 1124

【全球人口数据集】全球人口密度数据集GPWv4

全球人口密度数据集GPWv4

WW、forever的博客 1012

2025年下半年网络工程师案例分析真题及答案解析

2025年下半年网络工程师案例分析真题及答案解析

鹿鸣天涯 1106

hdu3117-Fibonacci Numbers

http://acm.hdu.edu.cn/showproblem.php?pid=3117 后四位存在周期15000,所以就打表打出了后四位的值。 前四位按照Fibonacci的通项公式取前四位即可 #include #include #include #include using namespace std; int fi[ 100 ] = { 0 , 1 , 1 } ; int L

luckycoding的专栏 852

软件设计师高频考点—套路题

学习交流的总结

秩沅 2546

HDU 3117 Fibonacci Numbers

题目链接 : HDU3117 Fibonacci Numbers Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) Total Submission(s): 1311    Accepted Submission(s): 549 Problem Descript

Salvare219 612

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

Fibonacci Numbers HDU3117

用了提取大数前四位和矩阵快速幂。  /*矩阵快速幂*/ #include&lt;iostream&gt; #include&lt;cstdio&gt; #include&lt;cstring&gt; #include&lt;cmath&gt; #include&lt;algorithm&gt; using namespace std; //const int mod = 10000; typ...

❂ 245

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

HDU-3117-Fibonacci Numbers

HDU-3117-Fibonacci Numbers 传送门 这道题是矩阵快速幂的经典题(入门级)+fib的求前四位数的方法 题目大意:求fib的第n项。如果没有超过8位,那么正常输出,如果超过了8位,就输出前四位数+…+后四位数 然后这个地方可以先枚举打表一下什么时候哪一项超过了8位数。 可以看到第40项以后才会超过8位数,所以前四十项直接预处理就可以啦~ 之后的输出前四项的方法请先参考博客方...

qq_44624316的博客 204

efm32 入门.pdf

本PDF共计22页,介绍的是操作驱动API,下载与否自己斟酌。

Hdu 3117 Fibonacci Numbers

题目地址:http://acm.hdu.edu.cn/showproblem.php?pid=3117 解题思路: 很显然费波纳数的后四位存在周期,通过测试可以发现后四位的周期为15000,所以后四位可以打表得出, 前四位是参考了别人的思路才做出来的。 因为费波纳数f[n] = 1/sqrt(5)(((1+sqrt(5))/2)^n+((1-sqrt(5))/2)^n). 很显然当n非常

为编程而生 823

【ICPC-235】hdu 3117 Fibonacci Numbers

点击打开hdu 3117 思路: 矩阵快速幂 分析: 1 题目要求的是求F(n)中如果位数的个数大于8那么要输出前4四位和后四位,没有到8位的时候直接输出 2 根据题目的样例我们可以知道当n = 40的时候就超过8位了,所以我们可以知道n <= 39的时候直接去求F(n),超过40的时候我们就要去求前4位和后四位 3 我们利用矩阵快速幂可以很快的求出后四位,但是前面四位就很困难了 ...

藏经阁 | 玄苦 1630

HDU - 3117 Fibonacci Numbers

题目链接:题目链接:题目链接:HDU - 3117 Fibonacci Numbers 解题思路:解题思路:解题思路: 前四十位(打表或者矩阵快速幂) 后四十位 后四位 前四位 我们通过将40位之前的fib打表出来后可以看出,40位之前的fib都是都是小于8位的。 对于前四十位fib可以打表输出,也可以参考之前写的矩阵快速幂求出 对于四十位往后的 对于后四位,我们依然可以通过矩阵快速幂求出之后对10000求余得到,但是对于前四位呢? 下面给大家介绍一个数学方法: Fib通项公式:Fn=15[(1

lymww的博客 275

hdu3117Fibonacci Numbers

写了一天的斐波那契你这是要我死啊

Code of Duty 730

【HDU3117】Fibonacci Numbers

【HDU3117】Fibonacci Numbers 题面 求斐波那契数列的第\(n\)项的前四位及后四位。 其中\(0\leq n<2^{32}\) 题解 前置知识:线性常系数齐次递推 其实后四位还是比较好求,矩阵快速幂就可以了,主要是前四位。 先用线性常系数齐次递推求出斐波那契数列的通项公式 \[ f_n=\frac{\sqrt 5}{5}\left((\frac{1+\sqr...

100

hdu3117 Fibonacci Numbers

题目(http://acm.hdu.edu.cn/showproblem.php?pid=3117) 求斐波拉契数的前四位和后四位,如果不超过八位就直接输出; 求前四位以前就做过,(http://blog.csdn.net/aonaigayiximasi/article/details/47615789) 老师教的矩阵连乘感觉很是巧妙啊,原来线性代数也是很有用的。 最后的矩阵的[0][1

skymeteorite 378
上一篇: hdu 2089 不要62
下一篇: hdu 4901 The Romantic Hero
Kefault
博客等级 码龄14年 19粉丝 210原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值