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:
Quick Guide to @RestClientTest in Spring Boot
Composition, Aggregation, and Association in Java
Request Method Not Supported (405) in Spring
How to Replace Many if Statements in Java
Java Stream Filter with Lambda Expression
Spring REST with a Zuul Proxy
Java Program to Compute Discrete Fourier Transform Using the Fast Fourier Transform Approach
Guide to DelayQueue
Encode/Decode to/from Base64
Converting String to Stream of chars
Hướng dẫn Java Design Pattern – Flyweight
Basic Authentication with the RestTemplate
Lớp Collections trong Java (Collections Utility Class)
Java – Convert File to InputStream
Làm thế nào tạo instance của một class mà không gọi từ khóa new?
Java Program to Implement the Alexander Bogomolny’s UnOrdered Permutation Algorithm for Elements Fro...
Java Program to Perform Complex Number Multiplication
Hướng dẫn Java Design Pattern – Command
Programmatic Transaction Management in Spring
Anonymous Classes in Java
Java Program to Implement Singly Linked List
Java Program to Solve any Linear Equations
HttpClient 4 – Follow Redirects for POST
Spring Boot - Unit Test Cases
Sorting in Java
A Guide To UDP In Java
Difference Between Wait and Sleep in Java
Java Program to Implement Adjacency List
Java Program to Check if a Given Set of Three Points Lie on a Single Line or Not
Hướng dẫn Java Design Pattern – State
Performance Difference Between save() and saveAll() in Spring Data
Spring Security 5 – OAuth2 Login