Using iteration to develop permissions

I am basically trying to rewrite math.pow, I have the following, obviously I am not getting the concept of return values. What am I doing wrong?

public static int power(int x, int n) { if (n == 0) return 1; int i,total; for(i = 0; i < n-1 ;i++); { total = (x * total); } return total; } 
+4
source share
6 answers

You need to initialize the total value to 1.

 int total = 1; 

You can simply rewrite everything to:

 public static int power(int x, int n) { int total = 1; for(int i = 0; i < n; i++) // i can be declared here directly { total = (x * total); } return total; // total remains 1 if n = 0 } 
+4
source
 public static int power(int x, int n) { int total = 1; // Initialized total to 1 for(int i = 0; i < n; i++) { total = x*total; } return total; } 
+3
source

instead of i < n-1 you should use i <= n-1 or i < n and int total=1 . hope it works.

also delete ; from the end of the for loop. rewriting code

 public static int power(int x, int n){ int total=1; for(int i = 0;i < n;i++) total *= x; return total; } 
+2
source

The value of the variable starts at 0. So the call to total = x*total will always be 0.

You need to initialize the total to x.

+1
source

First, it looks like you meant:

 if (n == 0) return 1; 

check the power, not the base number.

You are not initialisign total , using total = x to fix what I think.

+1
source

Here is a solution with log (n) complexity instead of linear. However, be careful with overflow.

 int pow(int x, int n) { int res = 1; while(n > 0) { if(n % 2 == 1) { res = res * x; } x = x * x; n = n / 2; } return res; } 
0
source

Source: https://habr.com/ru/post/1388740/


All Articles