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:
Send email with JavaMail
Guide to the Volatile Keyword in Java
Jackson Date
Java Program to Implement Treap
Transactions with Spring and JPA
Immutable Objects in Java
Introduction to the Java NIO2 File API
Java Program to Implement the Binary Counting Method to Generate Subsets of a Set
So sánh ArrayList và LinkedList trong Java
Converting a Stack Trace to a String in Java
Java Program to Implement Threaded Binary Tree
Tìm hiểu về Web Service
Phân biệt JVM, JRE, JDK
Java Program to Implement Min Heap
Java Program to Implement Meldable Heap
Một số nguyên tắc, định luật trong lập trình
Java Program to Perform Insertion in a 2 Dimension K-D Tree
Một số từ khóa trong Java
A Guide to JUnit 5
Java Program to Perform Cryptography Using Transposition Technique
Login For a Spring Web App – Error Handling and Localization
Function trong Java 8
Giới thiệu Google Guice – Aspect Oriented Programming (AOP)
A Guide To UDP In Java
Java Program to Implement Quick Sort Using Randomization
Guide to WeakHashMap in Java
A Guide to Queries in Spring Data MongoDB
Wrapper Classes in Java
Mệnh đề if-else trong java
Java Program to Implement WeakHashMap API
Optional trong Java 8
Immutable Map Implementations in Java