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 Program to Represent Graph Using Adjacency List
Java Convenience Factory Methods for Collections
Intro to the Jackson ObjectMapper
Hướng dẫn Java Design Pattern – Composite
Spring Security Authentication Provider
Java Program to Implement Fermat Primality Test Algorithm
Java Program to Implement Binary Tree
Apache Commons Collections MapUtils
Java – Random Long, Float, Integer and Double
How to Add a Single Element to a Stream
Java Program to Implement Splay Tree
Java Program to Find Inverse of a Matrix
Java Program to Emulate N Dice Roller
Java Program to Generate N Number of Passwords of Length M Each
Guide to Escaping Characters in Java RegExps
Guide to the Synchronized Keyword in Java
Java Program to Implement Leftist Heap
A Guide to HashSet in Java
Spring WebClient Requests with Parameters
The StackOverflowError in Java
Java Program to Implement Sieve Of Eratosthenes
Java Program to Implement Find all Back Edges in a Graph
Cơ chế Upcasting và Downcasting trong java
Guide to Spring 5 WebFlux
Java Program to Implement PriorityQueue API
Từ khóa throw và throws trong Java
Properties with Spring and Spring Boot
Converting Strings to Enums in Java
Java Program to Generate a Random Subset by Coin Flipping
Java Program to Implement LinkedHashMap API
HttpClient with SSL
Hướng dẫn sử dụng Java Annotation