I recently stumbled on this Project Euler Problem #25:
The 12th term, F12, is the first term to contain three digits.
What is the first term in the Fibonacci sequence to contain 1000 digits?
I just know C++98 and no other programming language. I have tried to solve it, making changes to get support of c++11.
Working:
#include <iostream>
#include<cstdio>
long len(long); //finding length
int main()
{
/* Ques: What is the first term in fibonacci series to contain 1000 digits? */
int ctr=2;
unsigned long first, second, third, n;
first=1;
second=1;
std::cout<<"\t **Project EULER Question 25**\n\n";
for(int i=2;;++i)
{
third=first+second;
// cout<<" "<<third;
int x=len(third);
// cout<<" Length: "<<x;
// cout<<"\n";
first=second;
second=third;
ctr++;
if(x>1000) // for small values, program works properly
{
std::cout<< " THE ANSWER: "<< ctr;
system("pause");
break;
}
}
}
long len(long num)
{
int ctr=1;
while(num!=0)
{
num=num/10;
if(num!=0)
{
ctr++;
}
}
return(ctr);
}
I know this is brute force, but can i make it more efficient so that i get the answer ?
Any help will be greatly appreciated.
EDIT:
By using Binet's Formula, as suggested by PaulMcKenzie and implementing it as:
#define phi (1+sqrt(5))/2
int main(void)
{
float n= ((999 + (1/2)*log10(5))/(log10(phi))); //Line 1
cout<<"Number is : "<<n;
return 0;
}
Output: 4780.187012
Changing Line 1, above, to :
float n= ((999 + log10(sqrt(5)))/(log10(phi)));
OUTPUT: 4781.859375
What could be possibly the error here?