Skip to content

Instantly share code, notes, and snippets.

@EmmaAkin EmmaAkin/isPrime.rb
Last active Sep 29, 2016

Embed
What would you like to do?
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
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
You can’t perform that action at this time.