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:
Deploy a Spring Boot App to Azure
Java Program to Implement LinkedBlockingDeque API
Removing all Nulls from a List in Java
Tính đa hình (Polymorphism) trong Java
Java Program to Implement CountMinSketch
Java Program to subtract two large numbers using Linked Lists
Comparing Objects in Java
Java Program to Implement Tarjan Algorithm
Java Program to Implement CopyOnWriteArrayList API
Write/Read cookies using HTTP and Read a file from the internet
The SpringJUnitConfig and SpringJUnitWebConfig Annotations in Spring 5
What is a POJO Class?
Interface trong Java 8 – Default method và Static method
Java Program to Implement Sorted Vector
Java Program to Find the GCD and LCM of two Numbers
Java Program to Implement LinkedTransferQueue API
Java Program to Implement String Matching Using Vectors
Java Program to Generate All Possible Combinations Out of a, b, c, d, e
Optional trong Java 8
Read an Outlook MSG file
Rest Web service: Filter và Interceptor với Jersey 2.x (P2)
Adding Parameters to HttpClient Requests
Configuring a DataSource Programmatically in Spring Boot
Java 8 Predicate Chain
Use Liquibase to Safely Evolve Your Database Schema
Java Program to Repeatedly Search the Same Text (such as Bible by building a Data Structure)
Converting a List to String in Java
Getting a File’s Mime Type in Java
A Guide to the finalize Method in Java
Check if a String is a Palindrome in Java
Java Program to Perform LU Decomposition of any Matrix
Java Program to Implement the One Time Pad Algorithm