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:
Java Convenience Factory Methods for Collections
Guide to PriorityBlockingQueue in Java
Entity To DTO Conversion for a Spring REST API
Java Program to Implement Binary Tree
Multi Dimensional ArrayList in Java
Java Program to Implement Ternary Search Algorithm
Converting Between Byte Arrays and Hexadecimal Strings in Java
Transactions with Spring and JPA
Introduction to Spring Method Security
Java Program to Implement Dijkstra’s Algorithm using Queue
Hướng dẫn Java Design Pattern – Transfer Object
Java Program to Generate a Random UnDirected Graph for a Given Number of Edges
Java Program to Perform Insertion in a BST
Base64 encoding và decoding trong Java 8
Spring Boot - Quick Start
New Features in Java 12
Spring Boot - Google OAuth2 Sign-In
HashMap trong Java hoạt động như thế nào?
Java Program to Implement CountMinSketch
Java InputStream to String
Java Program to Implement Suffix Tree
Control Structures in Java
Creating a Custom Starter with Spring Boot
Registration with Spring Security – Password Encoding
Chuyển đổi giữa các kiểu dữ liệu trong Java
Hướng dẫn Java Design Pattern – Visitor
HashSet trong java
Java – Write an InputStream to a File
Call Methods at Runtime Using Java Reflection
Java – InputStream to Reader
Extra Login Fields with Spring Security
Java Program to Implement PriorityBlockingQueue API