Blue Bridge Cup entry practice --Fibonacci the number of columns and optimize the use of

Problem description
the Fibonacci recursion formula: Fn = Fn-1 + Fn -2, where F1 = F2 = 1.

When n is relatively large, Fn is very great, and now we want to know, Fn is divided by the number 10007 is.

Input format
input contains an integer n.
Output format
output one line containing an integer representing the Fn remainder of the division of 10007.
Description: In this problem, the answer is to require Fn is divided by 10007, so we can figure this out as long as the remainder can be, without the need to calculate the exact value of Fn, then the result is calculated by dividing the number 10007 to take over direct calculation the remainder often than first calculate the original number and then take the remainder simple.

Input Sample
10
Sample output
55
Sample Input
22
sample output
7704
data size and Conventions
1 <= n <= 1,000,000.

Here we take a look at the code.

Code One:

#include <stdio.h>
#include <stdlib.h>

int fibon(int n);
int fibon(int n){
	if ((n==1) || (n==2))
		return 1;
	if (n > 2)
		return fibon(n-1) + fibon(n-2);
}
int main(int argc, char *argv[]) {
	int  m, n;
	
	scanf("%d",&m);
	n = fibon(m) % 10007;
	printf("%d",n);
	return 0;
}

You might write code that looks like this ,,,. Yes, you write, the following will tell you some of the relevant parameters and let you know you write code to look like.

Evaluation results of running overtime
scoring 30
the CPU use time out
memory usage 61.83MB

So, programming is not you write code to run successful even if you cross the border, in fact, you also need to think about how it can be optimized to make the code more concise! This will probably involve related algorithms, come on!
Let's look at another way, and related parameters.
Code II:

#include <stdio.h>
int main ()
{
	int n;
	scanf("%d",&n);
	int Fibonacci[n];
	int answer,i;
	for(i=1;i<=n;i++)
	{
		if(i<=2) 
			Fibonacci[i]=1;
		else 
			Fibonacci[i]=(Fibonacci[i-1]+Fibonacci[i-2])%10007;
	}
	answer=Fibonacci[n];
	printf("%d",answer);
	return 0;
}

Evaluation results are correct
score 100
the CPU using 31ms
memory usage 4.625MB

Comparison between the two could not contain himself spurting heart really wanted it,
in fact, the reason is very simple, is to write well, think of ways to optimize.
Haha, come to learn!
It is very simple introductory exercises Oh
~ I will continue to share the title race training with you! Come fight it together!

Guess you like

Origin blog.csdn.net/weixin_44566432/article/details/88414096