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:
Object cloning trong java
A Guide to JUnit 5 Extensions
Summing Numbers with Java Streams
Hướng dẫn Java Design Pattern – Flyweight
Java Program to Represent Linear Equations in Matrix Form
Introduction to Spring Data JPA
Java Program to Implement Expression Tree
Guide to CountDownLatch in Java
Java Program to Perform Postorder Recursive Traversal of a Given Binary Tree
Tránh lỗi ConcurrentModificationException trong Java như thế nào?
Java Program to Implement Trie
Java Program to Implement Heap
Java Program to Find Location of a Point Placed in Three Dimensions Using K-D Trees
Introduction to Spring Boot CLI
Java Program to Compare Binary and Sequential Search
Java Program to Represent Graph Using Linked List
Giới thiệu Java 8
Create Java Applet to Simulate Any Sorting Technique
Sử dụng Fork/Join Framework với ForkJoinPool trong Java
Map Serialization and Deserialization with Jackson
Java Program to Describe the Representation of Graph using Adjacency Matrix
Introduction to the Java ArrayDeque
Java – Try with Resources
Spring REST API + OAuth2 + Angular
Spring Cloud Series – The Gateway Pattern
Filtering and Transforming Collections in Guava
Java – Write to File
Cài đặt và sử dụng Swagger UI
Marker Interface trong Java
Java Program to Compute Cross Product of Two Vectors
The Spring @Controller and @RestController Annotations
Ép kiểu trong Java (Type casting)