Created
September 11, 2012 07:46
-
-
Save arn-e/3696743 to your computer and use it in GitHub Desktop.
Newton Fibonacci
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'benchmark' | |
def is_fibonacci?(i) | |
a,b=0,1 | |
until b >= i | |
a,b=b,a+b | |
return true if b == i | |
end | |
end | |
puts Benchmark.measure {is_fibonacci?(28657)} | |
puts Benchmark.measure {is_fibonacci?(638817435613190341905763972389505493)} | |
#Results : | |
# 0.000000 0.000000 0.000000 ( 0.000012) | |
# 0.000000 0.000000 0.000000 ( 0.000085) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'benchmark' | |
def is_fibonacci?(i) | |
x, x1 = 5 * (i * i) + 4, 5 * (i * i) - 4 | |
y, y1 = (newton_root(5 * (i * i) + 4)).to_i, (newton_root(5 * (i * i) - 4)).to_i | |
(y**2) == x || (y1**2) == x1 ? true : false | |
end | |
def newton_root(n) | |
guess1 = (Math.sqrt(n)).to_i | |
while n > 0 | |
guess2 = (n/guess1 + guess1)/2 | |
return guess2 if guess1 - guess2 < 0.5 | |
guess1 = guess2 | |
end | |
return guess2 | |
end | |
puts Benchmark.measure {is_fibonacci?(28657)} | |
puts Benchmark.measure {is_fibonacci?(638817435613190341905763972389505493)} | |
# Results : | |
# 0.000000 0.000000 0.000000 ( 0.000032) | |
# 0.000000 0.000000 0.000000 ( 0.000057) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment