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:
Default Password Encoder in Spring Security 5
Java Program to Represent Graph Using Incidence List
Java Program to Implement Unrolled Linked List
Filtering a Stream of Optionals in Java
Spring Security 5 for Reactive Applications
Java Program to Check whether Graph is a Bipartite using DFS
Java Program to Perform Search in a BST
Java TreeMap vs HashMap
Java Program to Implement Hash Tables with Linear Probing
Java Program to Implement ConcurrentLinkedQueue API
The Spring @Controller and @RestController Annotations
Java Program to Implement ScapeGoat Tree
Java Program to Implement Sorting of Less than 100 Numbers in O(n) Complexity
Guide to DelayQueue
Spring WebClient and OAuth2 Support
So sánh ArrayList và Vector trong Java
Java Program to Find the Minimum value of Binary Search Tree
Java Program to Implement the Program Used in grep/egrep/fgrep
Java Program to Implement Min Heap
Giới thiệu Aspect Oriented Programming (AOP)
Introduction to Spring Cloud CLI
Guide to Escaping Characters in Java RegExps
OAuth 2.0 Resource Server With Spring Security 5
Extract links from an HTML page
Giới thiệu Java Service Provider Interface (SPI) – Tạo các ứng dụng Java dễ mở rộng
Java Program to Solve Tower of Hanoi Problem using Stacks
New Features in Java 8
Java Program to Perform Inorder Non-Recursive Traversal of a Given Binary Tree
Hướng dẫn Java Design Pattern – Interpreter
Introduction to Spring Data JDBC
Java Program to Implement Euclid GCD Algorithm
Partition a List in Java