# Because the target number is relatively small, we simply compute each Fibonacci number starting # from the beginning until we encounter one with exactly 1000 digits. The Fibonacci sequence grows # exponentially with a base of about 1.618, so the numbers in base 10 will lengthen by one digit # after every log10(1.618) ~= 4.78 steps on average. This means the answer is at index around 4780. defcompute(): DIGITS = 1000 prev = 1 cur = 0 for i in itertools.count(): # At this point, prev = fibonacci(i - 1) and cur = fibonacci(i) if len(str(cur)) > DIGITS: raise RuntimeError("Not found") elif len(str(cur)) == DIGITS: return str(i) # Advance the Fibonacci sequence by one step prev, cur = cur, prev + cur
if __name__ == "__main__": print(compute())
Ruby
1 2 3 4 5 6 7 8
#!/usr/bin/env ruby i = 1 t1, t2 = 0, 1 while t2.to_s.length < 1000 t1, t2 = t2, t1 + t2 i += 1 end puts i
(* * Because the target number is relatively small, we simply compute each Fibonacci number starting * from the beginning until we encounter one with exactly 1000 digits. The Fibonacci sequence grows * exponentially with a base of about 1.618, so the numbers in base 10 will lengthen by one digit * after every log10(1.618) ~= 4.78 steps on average. This means the answer is at index around 4780. *) digits = 1000; i = 0; While[Fibonacci[i] < 10^(digits-1), i++] i
publicfinalclassp025implementsEulerSolution{ publicstaticvoidmain(String[] args){ System.out.println(new p025().run()); } /* * Because the target number is relatively small, we simply compute each Fibonacci number starting * from the beginning until we encounter one with exactly 1000 digits. The Fibonacci sequence grows * exponentially with a base of about 1.618, so the numbers in base 10 will lengthen by one digit * after every log10(1.618) ~= 4.78 steps on average. This means the answer is at index around 4780. */ privatestaticfinalint DIGITS = 1000; public String run(){ BigInteger lowerThres = BigInteger.TEN.pow(DIGITS - 1); BigInteger upperThres = BigInteger.TEN.pow(DIGITS); BigInteger prev = BigInteger.ONE; BigInteger cur = BigInteger.ZERO; for (int i = 0; ; i++) { // At this point, prev = fibonacci(i - 1) and cur = fibonacci(i) if (cur.compareTo(upperThres) >= 0) thrownew RuntimeException("Not found"); elseif (cur.compareTo(lowerThres) >= 0) return Integer.toString(i); // Advance the Fibonacci sequence by one step BigInteger temp = cur.add(prev); prev = cur; cur = temp; } } }