// Efficient Method : Time Complexity : θ(logn), Auxiliary Space: θ(1) import java.io.*; import java.util.*; public class Main { static int power(int x, int n) { int res = 1; while(n>0) { if(n%2 != 0) { res = res * x; x = x*x; n = n/2; } else { x = x*x; n = n/2; } } return res; } public static void main (String[] args) { int x = 3, n = 4; System.out.println(power(x, n)); } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter