Skip to content

Commit

Permalink
Merge pull request #1930 from Natan7/power_function
Browse files Browse the repository at this point in the history
Power in Ruby
  • Loading branch information
shoaibrayeen authored Oct 4, 2023
2 parents ea6d085 + 0ab3793 commit 33f9d82
Showing 1 changed file with 27 additions and 0 deletions.
27 changes: 27 additions & 0 deletions Basic/Implement Power Function/SolutionByNatan7.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
def get_power (base = 0, n = 1)
if n == 0
return 1
elsif ((n%2)==0)
return get_power(base*base, n/2)
else
return base*get_power(base*base, n/2)
end

end

# Take a number and the exponent value from the user as input and output the the result of expression (number^n)
print("Base: ")
base = gets.chomp.to_i
print("Power: ")
power = gets.chomp.to_i
n = power
if power<0
n = -1*power
end

result = get_power(base, n)

if power<0
result = 1.0/result
end
print("The result of " + base.to_s + "^" + power.to_s + " is "+ result.to_s + "\n")

0 comments on commit 33f9d82

Please sign in to comment.