-
-
Notifications
You must be signed in to change notification settings - Fork 362
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #1930 from Natan7/power_function
Power in Ruby
- Loading branch information
Showing
1 changed file
with
27 additions
and
0 deletions.
There are no files selected for viewing
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
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") |