Showing posts with label Math problem. Show all posts
Showing posts with label Math problem. Show all posts

Fast Doubling method to find nth Fibonacci number

Before Fast Doubling Method, lets discuss some naïve method to find nth fibonacci number.
Fibonacci Table

1. Recursive Method :
Recursive method is quite known approach to count fibonacci number but its very slow.
Here is the formula to find nth fibonacci number ,
F(0) = 0;
F(1) = 1;
F(n) = F(n-1) + F(n-2) ;
As an example n = 6;
using this above table , F(n) = 5+3 = 8;
// Here is the sample program ,
Its complexity is O(2^n).



2. Iterative method :
This method is too popular but its also very slow to count large fibonacci number. Its use the same formula I have discussed avobe.
// Here is the sample program.
Its complexity O(n). 



3. Fast Doubling Method :
This is the faster method than the above two method. We have few methods to calculate fibonacci number in faster way. Out of them  matrix exponentiation is most commonly used concept. Another well known concept is fast doubling method. It is called fast doubling method because every time you will found the twice fibonacci number for each n.
Fast doubling is based on two formula.
F(2n) = F(n)[2*F(n+1) – F(n)]
F(2n + 1) = F(n)2 + F(n+1)2
Lets see an example, n = 4;
F(2*4) = F(4) [ 2*F(5) – F(4)]; // follow the above table
=> F(8) = F(4) [ 2*5 – 3];
=> F(8) = 3 * 7;
=> F(8) = 21; // Here we get the F(8) nth fibonacci number.
The 2nd equation is as same as it.
F(9) = F(4)2 +F(5)2  ;
=> F(9) = 32 +52 ;
=> F(9) = 34 ;
// Here is the program.
This code has a complexity of O(log n) which is way too faster than previously discussed function.



Please don't feel shy to comment to improve these program and if you have better program please let me know. 

Projecteuler -- 21 (Amicable numbers)

Solution :  If you don't understand the solution process I will recommend you to go my blog's algorithm section and search "Divisor কথন" and read it hope you will understand.


problem Description : Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n).
If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair and each of a and b are called amicable numbers.
For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220.
Evaluate the sum of all the amicable numbers under 10000.



Project Euler -- 48 (Self powers)

Problem : The series, 11 + 22 + 33 + ... + 1010 = 10405071317.
Find the last ten digits of the series, 11 + 22 + 33 + ... + 10001000.

My solution approach is,

first made a smaller version of the problem then I tried to solve it after solving this I was going to solve the bigger version.

// a. find out p=2^15

// b. print the last digit of p