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:
Java Program to Implement the Edmond’s Algorithm for Maximum Cardinality Matching
Optional trong Java 8
Hướng dẫn Java Design Pattern – Singleton
Tạo số và chuỗi ngẫu nhiên trong Java
Compare Two JSON Objects with Jackson
A Custom Data Binder in Spring MVC
Lớp lồng nhau trong java (Java inner class)
Giới thiệu Swagger – Công cụ document cho RESTfull APIs
Tips for dealing with HTTP-related problems
Java Program to Perform Preorder Non-Recursive Traversal of a Given Binary Tree
Java Program to Implement Suffix Tree
Java Program to Find Transpose of a Graph Matrix
Java 14 Record Keyword
How to Manually Authenticate User with Spring Security
Chuyển đổi giữa các kiểu dữ liệu trong Java
Netflix Archaius with Various Database Configurations
Java Program to Implement Direct Addressing Tables
String Operations with Java Streams
Check if there is mail waiting
Convert XML to JSON Using Jackson
JUnit 5 @Test Annotation
Test a REST API with Java
Java Program to Implement Sieve Of Eratosthenes
Java Program to Perform String Matching Using String Library
HashMap trong Java hoạt động như thế nào?
Java Program to Use rand and srand Functions
Working With Maps Using Streams
Spring Boot - Admin Server
Java Program to Use the Bellman-Ford Algorithm to Find the Shortest Path
ThreadPoolTaskExecutor corePoolSize vs. maxPoolSize
Spring – Injecting Collections
Java Program to Search Number Using Divide and Conquer with the Aid of Fibonacci Numbers