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:
How to Count Duplicate Elements in Arraylist
Netflix Archaius with Various Database Configurations
Java Program to Find Nearest Neighbor Using Linear Search
Send an email with an attachment
Java Program to Implement Hash Tables with Linear Probing
Inheritance and Composition (Is-a vs Has-a relationship) in Java
Serialization và Deserialization trong java
Java equals() and hashCode() Contracts
Spring Security Logout
Control the Session with Spring Security
Java 9 Stream API Improvements
Spring Boot Configuration with Jasypt
Convert Character Array to String in Java
Primitive Type Streams in Java 8
Life Cycle of a Thread in Java
Java Program to Decode a Message Encoded Using Playfair Cipher
Guide to @ConfigurationProperties in Spring Boot
Functional Interface trong Java 8
Entity To DTO Conversion for a Spring REST API
Spring WebFlux Filters
Java Program to Generate Random Partition out of a Given Set of Numbers or Characters
Java Program to Optimize Wire Length in Electrical Circuit
Java Program to Implement the Hill Cypher
Java Program to Implement Affine Cipher
Jackson – Unmarshall to Collection/Array
Java Program to Find the Edge Connectivity of a Graph
Spring Boot - Admin Server
New Features in Java 10
Jackson – Marshall String to JsonNode
Java Program to Implement Quick Sort Using Randomization
Performance Difference Between save() and saveAll() in Spring Data
Java Program to Solve a Matching Problem for a Given Specific Case