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:
Lớp TreeMap trong Java
Spring Boot - Building RESTful Web Services
TreeSet và sử dụng Comparable, Comparator trong java
Sort a HashMap in Java
A Quick Guide to Using Keycloak with Spring Boot
Java Program to Check the Connectivity of Graph Using BFS
Java Program to Test Using DFS Whether a Directed Graph is Weakly Connected or Not
Java Program to Generate Random Numbers Using Multiply with Carry Method
Understanding Memory Leaks in Java
Java Program to Use Above Below Primitive to Test Whether Two Lines Intersect
Immutable Map Implementations in Java
Java Program to Check Whether a Given Point is in a Given Polygon
Java Program to Implement a Binary Search Tree using Linked Lists
Java 8 Stream API Analogies in Kotlin
Spring Boot - Apache Kafka
Java Program to Construct an Expression Tree for an Postfix Expression
Java Program to Implement Horner Algorithm
Java Program to Perform Stooge Sort
Hướng dẫn sử dụng Lớp FilePermission trong java
Java Program to Implement Range Tree
Hướng dẫn Java Design Pattern – Transfer Object
The Registration API becomes RESTful
How to Change the Default Port in Spring Boot
Java – Byte Array to Reader
Guide to Guava Multimap
Introduction to Spring Boot CLI
Prevent Brute Force Authentication Attempts with Spring Security
Java Program to Represent Graph Using Incidence Matrix
Hướng dẫn Java Design Pattern – Flyweight
Spring Boot - Runners
Java Program to add two large numbers using Linked List
Get the workstation name or IP