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:
Setting Up Swagger 2 with a Spring REST API
Java Program to Emulate N Dice Roller
Spring WebClient vs. RestTemplate
Java Program to Compute the Area of a Triangle Using Determinants
Deploy a Spring Boot App to Azure
Abstract class và Interface trong Java
How to Manually Authenticate User with Spring Security
Java Program to Implement Maximum Length Chain of Pairs
How to Convert List to Map in Java
Java Program to Represent Graph Using Adjacency List
@DynamicUpdate with Spring Data JPA
Getting Started with GraphQL and Spring Boot
Java Program to Describe the Representation of Graph using Adjacency Matrix
REST Web service: HTTP Status Code và xử lý ngoại lệ RESTful web service với Jersey 2.x
Java Program to Implement SimpeBindings API
Hướng dẫn sử dụng Java Reflection
Hướng dẫn Java Design Pattern – Memento
Batch Processing with Spring Cloud Data Flow
Java Program to Implement TreeSet API
Java Program to Create a Minimal Set of All Edges Whose Addition will Convert it to a Strongly Conne...
Giới thiệu Google Guice – Injection, Scope
Java Program to Perform Quick Sort on Large Number of Elements
Queue và PriorityQueue trong Java
Java Program to Generate All Pairs of Subsets Whose Union Make the Set
Spring 5 WebClient
Java Program to Implement AA Tree
Hướng dẫn sử dụng Printing Service trong Java
So sánh HashMap và Hashtable trong Java
LinkedHashSet trong java
An Intro to Spring Cloud Contract
Java Program to Implement Dijkstra’s Algorithm using Priority Queue
Java Program to Implement Levenshtein Distance Computing Algorithm