Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Power implementation (any positive numbers) #214

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions maths/power.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
def power (number = 0, n = 1)
if number < 0 || n <0
return -1
end

if n == 0
return 1
elsif ((n%2)==0)
return power(number*number, n/2)
else
return number*power(number*number, 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("Enter a positive integer value (base):")
number = gets.chomp.to_i
print("Now, enter a positive integer value (exponent):")
n = gets.chomp.to_i

result = power(number, n)
if(result==-1)
puts "Sorry, Invalid Number! Negative number informed."
else
print("The result of " + number.to_s + "^" + n.to_s + " is "+ result.to_s + "\n")
end