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 Implement Gauss Seidel Method
Java Program to Represent Graph Using Linked List
Custom JUnit 4 Test Runners
Chuyển đổi Array sang ArrayList và ngược lại
Giới thiệu Google Guice – Binding
Hướng dẫn Java Design Pattern – Template Method
Comparing Arrays in Java
Assert an Exception is Thrown in JUnit 4 and 5
Hướng dẫn Java Design Pattern – Iterator
The Registration API becomes RESTful
Java Program to Repeatedly Search the Same Text (such as Bible by building a Data Structure)
Redirect to Different Pages after Login with Spring Security
Function trong Java 8
Spring Boot - Runners
Spring Data Java 8 Support
A Custom Data Binder in Spring MVC
Java Program to Implement Slicker Algorithm that avoids Triangulation to Find Area of a Polygon
Xử lý ngoại lệ trong Java (Exception Handling)
Kết hợp Java Reflection và Java Annotations
Java Program to Check if a Given Graph Contain Hamiltonian Cycle or Not
Java Program to Perform Polygon Containment Test
Spring @RequestMapping New Shortcut Annotations
Convert Character Array to String in Java
Java Program to Implement Maximum Length Chain of Pairs
Guide to UUID in Java
Immutable Map Implementations in Java
Java Copy Constructor
Java Program to Generate All Pairs of Subsets Whose Union Make the Set
Java Program for Douglas-Peucker Algorithm Implementation
Java Program to Implement LinkedBlockingQueue API
New Features in Java 10
Properties with Spring and Spring Boot