Mathematics gfg04

 package com.company;


import java.util.Scanner;

public class CWR_Mathematics04 {
// Iterative approach( binary exponentiation)
public 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;
}
return res;
}
// computing power 2
public static int computingPower(int x,int n){
if (n==0){
return 1;
}
int temp = computingPower(x,n/2);
temp = temp*temp;
if(n%2==0){
return temp;
}
else
return temp*x;
}
// computing power 1
public static int printPower(int x,int n){
if(n==0){
return 1;
}
int temp = 1;
for(int i=1;i<=n;i++){
temp = temp*x;
}
return temp;
}
public static void main(String[] args) {
System.out.println("Enter the number");
Scanner sc = new Scanner(System.in);
System.out.println(printPower(sc.nextInt(),sc.nextInt()));
}
}

Comments