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 Show the Duality Transformation of Line and Point
Intro to the Jackson ObjectMapper
Spring Boot - Enabling Swagger2
Guide to the Volatile Keyword in Java
Java Program to Implement Miller Rabin Primality Test Algorithm
Case-Insensitive String Matching in Java
Java Program to implement Bit Matrix
Spring Data JPA and Null Parameters
Java Program to Implement Hash Tables Chaining with Binary Trees
Weak References in Java
Sorting in Java
Mix plain text and HTML content in a mail
Java Program to Implement Max Heap
How to Return 404 with Spring WebFlux
Hướng dẫn Java Design Pattern – Command
Java Program to Implement Binary Search Tree
So sánh HashSet, LinkedHashSet và TreeSet trong Java
Convert String to Byte Array and Reverse in Java
Intro to Spring Boot Starters
Java Program to Generate Random Partition out of a Given Set of Numbers or Characters
Configure a Spring Boot Web Application
Guide to Mustache with Spring Boot
Spring Boot - Web Socket
Spring JDBC
Servlet 3 Async Support with Spring MVC and Spring Security
Remove the First Element from a List
Lớp Collections trong Java (Collections Utility Class)
Java Program to Implement a Binary Search Algorithm for a Specific Search Sequence
Java Program to Implement Merge Sort on n Numbers Without tail-recursion
Uploading MultipartFile with Spring RestTemplate
A Guide to JUnit 5 Extensions
Java Program to Implement CopyOnWriteArraySet API