Last active
September 29, 2016 19:39
-
-
Save pensebien/0aebb88bcb1319c3cd1b88131bd78f46 to your computer and use it in GitHub Desktop.
This is a ruby code that check if the number you typed is a prime using the fastest method ever. Hint! Use square root algorithm
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
puts "Enter a number to to check" | |
number = gets.chomp.to_i | |
def abs(firstNum,secNum) | |
if firstNum > secNum | |
firstNum - secNum | |
else | |
secNum - firstNum | |
end | |
end | |
def square (x) | |
x * x | |
end | |
def sqrt(x,d) | |
max = x/2.0 | |
min = 0 | |
mid = x/2.0 | |
while max-min > d | |
mid = (max+min)/2 | |
if square(mid)-x>0 | |
max = mid | |
else | |
min = mid | |
end | |
end | |
mid | |
end | |
def isPrime(prime) | |
square = (sqrt(prime,0.000001)).floor | |
n= 2 | |
result = true | |
while n <=square | |
if prime%n ==0 | |
return result = false | |
end | |
n +=1 | |
end | |
result | |
end | |
puts isPrime(number) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment