From 9c53748e4ee058d86a02b9478fd161dc58c84e0b Mon Sep 17 00:00:00 2001 From: Santo Cariotti Date: Wed, 19 Aug 2020 21:25:52 +0200 Subject: Update pow.cc better solution with O(n) --- I_anno/Programmazione_2/algorithms/pow.cc | 29 ++++++++++------------------- 1 file changed, 10 insertions(+), 19 deletions(-) (limited to 'I_anno') diff --git a/I_anno/Programmazione_2/algorithms/pow.cc b/I_anno/Programmazione_2/algorithms/pow.cc index 70f5b43..16cf419 100644 --- a/I_anno/Programmazione_2/algorithms/pow.cc +++ b/I_anno/Programmazione_2/algorithms/pow.cc @@ -2,29 +2,20 @@ using namespace std; -int pow(int b, int e) { - if(e == 0) return 1; - int a = b; - int inc = b; - for(int i = 0; i < e-1; ++i) { - for(int j = 0; j < b-1; ++j) { - a+=inc; - } - inc = a; - } +int pow(int x, int y) { + int a = 1; + + for(int i = 0; i < y; ++i) + a*=x; + return a; } -int mul(int b, int e) { - if(e == 0) return 0; - return b+mul(b, e-1); -} - -int pow2(int b, int e) { - if(e == 0) return 1; - - return mul(b, pow(b, e-1)); +int pow2(int x, int y) { + if(y < 1) return 1; + + return x*pow(x, y-1); } int main() { -- cgit v1.2.3-18-g5258