Fibonacci sequence and inverse calculation problems

Source: Internet
Author: User

Inverse calculation: Write a function to convert an integral type to a binary form

Inverse calculation problem, recursion is simpler than loop

Analysis: Need to understand that the last digit of the odd binary is 1, even the binary last one must be 0, associative memory, this and the parity of the integer is consistent, 1 itself is odd, 0 itself is an even number.


decimal integers are converted to binary integers using the "Divide 2, Reverse order" method. The specific method is: divisible by 2 decimal integers, you can get a quotient and the remainder, and then 2 to remove the quotient, and will get a quotient and the remainder, so proceed, until the quotient is 0 o'clock, and then the first obtained remainder as a binary number of the low-effective bit, the remainder as a binary number of the high effective bit, sequentially arranged. For the numeric n, the last =n%2 of the binary; The result of the calculation is the result of the final output, using the recursive function, the characteristics of the recursion:computes the n%2 before the recursive statement, outputting the result after the recursive invocation, so that the result is computed at the last output.

The remainder inversion method is used for the repeated division of 10-in-Turn 2-binary system;

1#include <stdio.h>2#include <stdlib.h>3 voidTobinary (unsignedLong);4 intMain ()5 {6UnsignedLongnum;7printf"Enter a positive integer: Q exits \ n");8      while(scanf_s ("%ul", &num) = =1)9     {Ten tobinary (num); OnePutchar ('\ n'); Aprintf"Enter a positive integer: \ n"); -     } -System"Pause"); the     return 0; - } - //Recursive Functions - voidTobinary (unsignedLongnum) + { -     intR; +r = num%2;//The last one to output, even if the parameter = 1, or to calculate to end here, only the remainder is OK. Then return to the top-level keynote function sequentially and continue with the rest ... A     //if quotient 1/2 = 0, calculation can be terminated, no need to calculate at     if(Num >=2) -     { -         //essence, contact 10 binary to 2 binary algorithm, each time divided by 2, take out the remainder, and then with the new quotient continue divided by 2, remove the Xinyu number ... Until the quotient is 0, the remainder will be output in reverse order -Tobinary (num/2);//recursive invocation of new quotient as parameters -     } -     //output after the recursive statement, this is the flashback output inprintf"%d", R); -}

Of course, this algorithm can also be implemented using bit manipulation:

//Converts an unsigned decimal number to a standard 16-bit binary numberintMain () {unsigned Shorti; cout<<"Please enter a positive integer less than 65536"<<Endl; CIN>>i; //The for statement is decremented from 15 to 0, with a total of 16 times the judgment of each bit of the binary number.      for(intj = the; J >=0; j--)    {        //The << operation indicates that the 1 binary form is shifted to the left of the whole J-position, and the left post is shifted to 0, and the high part of the shift is discarded.         if(I & (1<<j)) {            //the value of i& (1<<J) is equivalent to the J-bit of the binary of I (the J-bit of I and the J-bit of (1<<J) and the J-bit of I is the 1 value is true) after the loop has a binary form of I. cout <<"1"; }        Else{cout<<"0"; }} cout<<Endl; return 0;}

The << operation indicates that the 1 binary form is shifted to the left of the whole J-position, and the left post is shifted to 0, and the high part of the shift is discarded.

For example, when J is 15 o'clock, the expression (1<<J) has a value of 1000000000000000, and when J is 10 o'clock, the value is 0000010000000000.

Bitwise operation of the "personality" determines its direct data in the binary form of the operation of the fast (general computer data storage Basic form of binary form), two of the same algorithm program, using the bit operation will make the program speed improvement.

It's also possible to use a ready-made conversion function

_itoa (&buffer, 16); The first argument is the number to be converted, the second is the address, and the third is the binary number

See recursion again the pros and cons

Advantages: For some programming problems to provide a simple way, such as the above question and the Fibonacci number of questions, such as two numbers are 1, the rest of each number is the first two numbers and. This uses recursion very well.

Disadvantage: Occupy the memory big, consumes the resources, the speed is slow, the general difficulty maintains and reads. such as the Fibonacci sequence recursive function:

The Fibonacci sequence.

The origin of the problem: the 13th century Italian mathematician Fibonacci (Fibonacci) wrote a commercial Arithmetic and Algebra Handbook <<liber abaci>>. In this book, he raises such an interesting question:

Suppose a pair of rabbits can have a pair of rabbits after they have been born for a full two months, and then they can regenerate a couple of rabbits every one months. Suppose there are a couple of rabbits in a cage now, how many rabbits should there be in a cage in a year?

Let's make a careful calculation.

The first and second months, the rabbit grew into a big rabbit, but not mature enough to have a rabbit, so a total of only a pair.

The third month, the original pair of big rabbits gave birth to a pair of rabbits, now a total of two pairs.

The fourth month, the big Rabbit gave birth to a pair of rabbits, but the second generation of the small rabbit is not mature, but also can not give birth to a rabbit, so there are three pairs.

Fifth month, the first to second two generations of two pairs of rabbits each gave birth to a pair of rabbits, together with the original three in April, now a total of five.

The sixth month, in April already have three pairs of rabbits each have a pair of rabbits, together with the original five pairs of rabbits in May, now a total of eight pairs.

And so on, the logarithm of all rabbits per month should be equal to the total of all the rabbits in the last one months (that is, the logarithm of the original rabbit) and all the rabbits on the last month (the rabbits each gave birth to a pair of rabbits).

So each month the rabbit logarithm should be 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233 ...

Each item is the sum of the first two items. So, a year later, there should be 233 pairs of rabbits in the cage.

The number of these rabbits we call Fibonacci numbers (Fibonacci numbers).

For the sake of convenience, we use FN to denote the number of the nth-generation rabbits.

We observed that:

F1=f2=1

And when N≧3, fn=fn-1+fn-2

The simplest, but the most time-complexity solution is the recursive algorithm, the algorithm time Complexity O (n^2)

Long LongFibonaccirecursion (unsignedintN) {    if(0==N) {        return 0; }    Else if(1==N) {        return 1; }    Else{        returnFibonaccirecursion (N-1) + fibonaccirecursion (N-2); }}

Note: All functions in C and C + + have equal status and can be called by any other function while calling any other function. For example, while main is a program entry function, main can also be recursive, or called by other functions, but not often.

The process of this recursive Jiefepo sequence is analyzed below. In the case of F (10), in order to find F (10), F (9) and F (8) are required, in the same vein, F (9), F (8) and F (7) are obtained. Use a recursive tree to represent:

It is found that this is a double recursion, that is, each time the function has made two calls to itself (not one call at a time, but each recursive call to itself two times), so that the exponential variable order occurs, that is, each recursive call produced by the variable set is exponential growth, as shown in the recursive tree, many nodes are redundant, is wasteful. This makes it easy for the program to crash. This is a typical extreme example that reminds us to use caution and combine efficiency.

The way to improve it is to avoid repetitive calculations.

Intermediate results can be saved in advance for later use, the next time the calculation of the direct use, no need to repeat the calculation. Use the iterative recursion method.

//recursive solution, non-recursiveLong LongFibonaccirecursion (unsignedintN) {    //First Judge N=0 and 1.    if(0==N) {        return 0; }    Else if(1==N) {        return 1; }    Else    {        LongN0 =0; LongN1 =1; Longfn =0;  for(inti =2; I <= N; i++) {fn= n1 +N0; N0=N1; N1= FN;//This is a recursive process.        }                returnfn; }}

Algorithm time complexity O (n), very easy to understand, but also a very practical solution. In the actual development, the first recursive method is not used, because the efficiency is very low, and the second method (also the hormone iteration), the recursion uses the cyclic processing, greatly improves the time efficiency. More commonly used.

Some variants of Fibonacci.

Q: A frog can jump up a step at a time, or jump on a two-step stage at a time, and ask the frog to jump on an n-level step. How many hops are there in total?

Analysis

If there is only one step, then there is a jump method, two steps, then a total of two kinds of jumping method, false with n steps, then the Jump method is recorded as f (n), when the N>2, when the first jump when there are two options, if the first jump only one level, at this time the number of hops for the rest of the n-1 steps of the number of jumps, That is, F (n-1), if the first jump two levels, at this time the number of hops is the number of n-2 steps left behind, that is, F (n-2), so altogether f (n) =f (n-1) +f (n-2) species, in fact, is the Fibonacci sequence.

Q: With 2x1 small rectangular horizontal or vertical to cover the larger rectangle, ask 8 2x1 small rectangle without overlapping a large rectangular 2x8, how many ways?

The cover method of 2x8 is recorded as F (8), the first 1x2 small rectangle to cover the left side of the large rectangle two choices, vertical or horizontal, when the vertical put, the right side of the 2x7 a small area, in this case the coverage method is recorded as F (7), if horizontal, when the small 1x2 rectangle in the upper left corner, The lower left corner must also be placed sideways in a 1x2 small rectangle, and on the right side there is a 2x6 area, the coverage method is recorded as F (6), so F (8) =f (7) +f (6), which is still the Fibonacci sequence.

Fibonacci sequence and inverse calculation problems

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.