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:
Deque và ArrayDeque trong Java
Java Program to Find Number of Articulation points in a Graph
REST Web service: HTTP Status Code và xử lý ngoại lệ RESTful web service với Jersey 2.x
New Features in Java 8
Java Program to Implement Sieve Of Eratosthenes
Java Program to Implement Graham Scan Algorithm to Find the Convex Hull
Java – InputStream to Reader
Tính đa hình (Polymorphism) trong Java
Java IO vs NIO
Introduction to Spring Cloud Stream
Spring MVC Async vs Spring WebFlux
Java Program to Implement Double Order Traversal of a Binary Tree
Java Program to Implement the Hungarian Algorithm for Bipartite Matching
Java Program to Implement Hash Tables with Double Hashing
Java Program to Implement VList
Tổng quan về ngôn ngữ lập trình java
Java – Convert File to InputStream
Java Program to Check if a Given Binary Tree is an AVL Tree or Not
Guide to the Java ArrayList
Apache Commons Collections BidiMap
Java Program to Implement Flood Fill Algorithm
Spring Boot - Internationalization
Giới thiệu về Stream API trong Java 8
Basic Authentication with the RestTemplate
Java Program to Implement Queue using Linked List
Spring Boot - Scheduling
Java Program to Implement Hash Tables Chaining with Binary Trees
Java Program to Implement Dijkstra’s Algorithm using Queue
Merging Two Maps with Java 8
A Guide to Java HashMap
Converting a List to String in Java
Java Program to Generate All Subsets of a Given Set in the Lexico Graphic Order