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:
Check if there is mail waiting
Các kiểu dữ liệu trong java
How to Get All Spring-Managed Beans?
Java Program to Find the Peak Element of an Array O(n) time (Naive Method)
Java Program to Find Second Smallest of n Elements with Given Complexity Constraint
An Introduction to ThreadLocal in Java
Chuyển đổi từ HashMap sang ArrayList
Testing an OAuth Secured API with Spring MVC
A Guide to the finalize Method in Java
Java 8 – Powerful Comparison with Lambdas
Java Program to Implement ConcurrentHashMap API
Spring AMQP in Reactive Applications
Configure a Spring Boot Web Application
Java Program to Implement Floyd-Warshall Algorithm
Converting Java Date to OffsetDateTime
Java Program to Implement the One Time Pad Algorithm
Primitive Type Streams in Java 8
Java Program to Create the Prufer Code for a Tree
Abstract class và Interface trong Java
Spring Cloud AWS – Messaging Support
Java Program to Implement Sorted List
Java program to Implement Tree Set
Java Timer
Java Program to Implement Binary Search Tree
Spring WebClient Filters
Phương thức forEach() trong java 8
Java Program to Find the Connected Components of an UnDirected Graph
Java Program to Implement the Hungarian Algorithm for Bipartite Matching
Lập trình đa luồng với CompletableFuture trong Java 8
Split a String in Java
Java Program to Find the Minimum value of Binary Search Tree
Java Program to Implement Borwein Algorithm