Severity: Warning
Message: fopen(/tmp/ci_sessionrb1j2vkb6bgc6do3u27rnmf5v6sai4c6): failed to open stream: No space left on device
Filename: drivers/Session_files_driver.php
Line Number: 176
Backtrace:
File: /var/www/html/application/controllers/Project.php
Line: 10
Function: __construct
File: /var/www/html/index.php
Line: 311
Function: require_once
Severity: Warning
Message: session_start(): Failed to read session data: user (path: /tmp)
Filename: Session/Session.php
Line Number: 143
Backtrace:
File: /var/www/html/application/controllers/Project.php
Line: 10
Function: __construct
File: /var/www/html/index.php
Line: 311
Function: require_once
In this tutorial, we have to calculate the power of a number with minimum time complexity through recursion using the JAVA programming language.
The purpose of this project is to calculate the power of a given number with minimum time complexity through recursion in a JAVA programming language.
Recursion: Recursion is a method of solving a problem where the solution depends on solutions to smaller instances of the same problem.
Exponentiation is a mathematical operation, written as bn, involving two numbers, the base b, and the exponent or power n, and pronounced as "b raised to the power of n".[1][2] When n is a positive integer, exponentiation corresponds to repeated multiplication of the base: that is, bn is the product of multiplying n bases:
The below code is taking base and exponent as input from the user and then sending it as a parameter through calculatePower(num1, num2) function, calculating power through recursion, and returning the result.
import java.util.*;
public class fastestPowerCalculator {
static int calculatePower(int a, int b)
{
if(b==0)
{
return 1;
}
if(b%2==0)
{
return calculatePower(a*a,b/2);
}
else
{
return a*calculatePower(a,b-1);
}
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter base:");
int num1 = sc.nextInt();
System.out.println("Enter exponent:");
int num2 =sc.nextInt();
int result = calculatePower(num1 , num2);
System.out.println("Result is "+result);
}
}
Submitted by Kartik Rakesh Khandelwal (kkwal27)
Download packets of source code on Coders Packet
Comments