Skip to content

Instantly share code, notes, and snippets.

@pensebien
Last active September 29, 2016 19:39
Show Gist options
  • Save pensebien/0aebb88bcb1319c3cd1b88131bd78f46 to your computer and use it in GitHub Desktop.
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
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