Thinking efficiency Fibonacci number calculation triggered About

Fibonacci number Fibonacci sequence algorithm as follows:

int FibonacciFunc(int val)
{
	if(0 == val)
		return 0;
	else if(1 == val)
		return 1;
	
	return FibonacciFunc(val - 1) + FibonacciFunc(val - 2);
}

 The algorithm is not complicated, it is a recursion. But calls itself recursively been, which would involve the construction of stacks and stacks sales, cost is great, especially when the need to constantly call this recursive computation to do when that resource consumption, time used, will not be ignored . Suddenly I see this issue, start thinking about how to reduce this overhead. Of course, this thinking has nothing to do with the Fibonacci program of Number thought that the hidden matrix. We consider the probability of a problem. General dealing with the actual situation, there will be a lot of data is duplicated, there will be some probability of occurrence, we start from that point.

1, the lower and more resources can be deployed enough premise:

      The list is the best choice

typedef struct _FIBONACCI_VAL_MAP
{
	int item ;      //项
	int val;        //值
	struct _FIBONACCI_VAL_MAP *next;
}FIBONACCI_VAL_MAP;

Before each calculation, find out if there is a hit list data. If you do not hit on the calculated data, and inserted at the beginning of the list.

Wait until the program runs long enough, then the value of almost real situation can be found in the list. At this performance bottleneck will appear on the list lookup. For example, a tree to find? Further optimize it? Whether the tree is optimized lookup list after verification lookup. Recursion is consumed than before on the construction of the stack pin stack, list Find more is consumed in the register values ​​assigned. This is both time consuming than an order of magnitude

 

2, fewer resources:

   It would be an array of fixed size array,

typedef struct _FIBONACCI_VAL_MAP
{
	int item ;
	int val;
}FIBONACCI_VAL_MAP;

FIBONACCI_VAL_MAP Target_Map[10];

Find a list of programs to find as before, with the first hit of the members of the exchange. Add to miss the first, before the data after the shift, automatically discard the last (lowest hit probability).

3, other optimization program also did not expect. Empty glove White Wolf predecessors. Manual funny .jpg

Published 22 original articles · won praise 9 · views 8830

Guess you like

Origin blog.csdn.net/ljm_c_bok/article/details/82981100