From 60f8f489e8be47a40f334e1a87a03af96c2d8114 Mon Sep 17 00:00:00 2001 From: Natan7 Date: Mon, 2 Oct 2023 02:00:25 -0300 Subject: [PATCH] Power implementation (any positive numbers) --- maths/power.rb | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 maths/power.rb diff --git a/maths/power.rb b/maths/power.rb new file mode 100644 index 00000000..cb332295 --- /dev/null +++ b/maths/power.rb @@ -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