Created
September 29, 2016 22:50
-
-
Save kwekuboateng/016d65815738b4acb24041bf4181a535 to your computer and use it in GitHub Desktop.
This file contains 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
# 1. Check if a numbers is prime | |
def midpoint(a,b) | |
(a + b)/2.0 | |
end | |
def shrtcut(low,high,x) | |
guess = midpoint(low,high) | |
e_cmp = (guess * guess) - x | |
[guess,e_cmp] | |
end | |
def square_root(x,e) | |
if x == 1; | |
guess = 1 | |
else | |
low = 0 | |
high = x | |
guess,e_cmp = shrtcut(low,high,x) | |
until e_cmp <= e and e_cmp > 0 do | |
e_cmp < 0 ? low = guess : high = guess | |
guess,e_cmp = shrtcut(low,high,x) | |
end | |
guess | |
end | |
end | |
=begin | |
print "Enter x: " | |
x = Float $stdin.gets.chomp() | |
print "Enter Hazels no: " | |
e = Float $stdin.gets.chomp() | |
puts " The square root of #{x} is #{square_root(x,e)}" | |
=end | |
def is_prime(x, e) | |
root = square_root(x, e); | |
root = root.round | |
puts root | |
if x == 1 | |
puts 'not prime' | |
end | |
while root > 1 do | |
if x%root == 0 | |
puts "not prime" | |
return false | |
else | |
puts "prime" | |
return true | |
end | |
root = root - 1; | |
end | |
end | |
puts is_prime(4, 0.001) | |
#2. Product of individaul elements except current index | |
def product_of_other_elements_in_array_except_current_index(numbers) | |
product_array = [] | |
numbers.each_index { |index| | |
count = 0 | |
product = 1 | |
while count < numbers.length do | |
if count == index | |
numbers[count] = 1 | |
product = product * numbers[count] | |
else | |
product = product * numbers[count] | |
end | |
count+=1 | |
end | |
product_array[index] = product | |
} | |
end | |
puts product_of_other_elements_in_array_except_current_index([2,3,4]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment