This is a Java Program to Implement Repeated Squaring Algorithm. Repeated squaring algorithm is used to compute xn efficiently.
Here is the source code of the Java Program to Implement Repeated Squaring Algorithm. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.
/**
** Java Program to Implement Repeated Squaring Algorithm
**/
import java.util.Scanner;
/** Class RepeatedSquaring **/
public class RepeatedSquaring
{
/** Function for repeated squaring **/
public double expBySquaring(double x, int n)
{
if (n < 0)
return expBySquaring(1 / x, -n);
else if (n == 0)
return 1;
else if (n == 1)
return x;
else if (n % 2 == 0)
return expBySquaring(x * x, n / 2);
else
return x * expBySquaring(x * x, (n - 1)/2);
}
/** Main function **/
public static void main (String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Repeated Squaring Algorithm Test\n");
/** Make an object of RepeatedSquaring class **/
RepeatedSquaring rs = new RepeatedSquaring();
/** Accept n , k **/
System.out.println("\nEnter n and k of (N ^ K)");
double n = scan.nextDouble();
int k = scan.nextInt();
double result = rs.expBySquaring(n, k);
System.out.println("\nResult : "+ result);
}
}
Output:
Repeated Squaring Algorithm Test Enter n and k of (N ^ K) 3 19 Result : 1.162261467E9 Repeated Squaring Algorithm Test Enter n and k of (N ^ K) 7 -4 Result : 4.1649312786339016E-4
Related posts:
Guide to the Synchronized Keyword in Java
HandlerAdapters in Spring MVC
Java Program to Implement AttributeList API
Spring MVC Content Negotiation
Rest Web service: Filter và Interceptor với Jersey 2.x (P1)
Spring Security Login Page with React
Java Program to Implement Euclid GCD Algorithm
Java Program to Perform String Matching Using String Library
Mapping Nested Values with Jackson
Converting Java Date to OffsetDateTime
Add Multiple Items to an Java ArrayList
Custom Thread Pools In Java 8 Parallel Streams
Use Liquibase to Safely Evolve Your Database Schema
Java Program to Construct a Random Graph by the Method of Random Edge Selection
Hướng dẫn Java Design Pattern – DAO
Send an email with an attachment
StringBuilder vs StringBuffer in Java
Từ khóa this và super trong Java
Spring Boot - Exception Handling
Java Program to Check Whether a Directed Graph Contains a Eulerian Path
Java Program to implement Sparse Vector
Comparing Two HashMaps in Java
Java Program to Implement Bloom Filter
Biểu thức Lambda trong Java 8 – Lambda Expressions
Java Program to Implement Circular Doubly Linked List
The Difference Between map() and flatMap()
How to Replace Many if Statements in Java
Spring Cloud – Bootstrapping
Java Program to Create a Random Linear Extension for a DAG
Disable DNS caching
Java Program to Compute Discrete Fourier Transform Using the Fast Fourier Transform Approach
Java Program to Generate Random Numbers Using Multiply with Carry Method