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:
Getting the Size of an Iterable in Java
Getting Started with Custom Deserialization in Jackson
CyclicBarrier in Java
Spring MVC and the @ModelAttribute Annotation
Chuyển đổi Array sang ArrayList và ngược lại
Apache Commons Collections SetUtils
Java Program to Implement Sieve Of Eratosthenes
Spring Boot - OAuth2 with JWT
Database Migrations with Flyway
Giới thiệu Aspect Oriented Programming (AOP)
Hướng dẫn Java Design Pattern – DAO
How to Store Duplicate Keys in a Map in Java?
HttpClient 4 – Send Custom Cookie
Java Program to Implement RoleList API
Handling URL Encoded Form Data in Spring REST
Java Program to Implement Bit Array
Adding Parameters to HttpClient Requests
Guide to the Java Queue Interface
Stack Memory and Heap Space in Java
Java Program to Perform Preorder Recursive Traversal of a Given Binary Tree
Làm thế nào tạo instance của một class mà không gọi từ khóa new?
Spring Boot - CORS Support
A Guide to WatchService in Java NIO2
Tổng quan về ngôn ngữ lập trình java
Guide to Escaping Characters in Java RegExps
Check If Two Lists are Equal in Java
The Difference Between Collection.stream().forEach() and Collection.forEach()
Hướng dẫn Java Design Pattern – Object Pool
JUnit 5 @Test Annotation
Hướng dẫn Java Design Pattern – Singleton
Returning Image/Media Data with Spring MVC
Constructor Injection in Spring with Lombok