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:
Pagination and Sorting using Spring Data JPA
Map Interface trong java
Java Program to Implement Hash Tables with Double Hashing
Show Hibernate/JPA SQL Statements from Spring Boot
Anonymous Classes in Java
Spring Boot - Code Structure
Convert Time to Milliseconds in Java
Java Program to Represent Graph Using 2D Arrays
Spring Security Form Login
Java – Reader to Byte Array
Spring Data MongoDB Transactions
OAuth 2.0 Resource Server With Spring Security 5
Mệnh đề Switch-case trong java
Java Program to Generate Random Partition out of a Given Set of Numbers or Characters
ThreadPoolTaskExecutor corePoolSize vs. maxPoolSize
A Custom Data Binder in Spring MVC
Hướng dẫn Java Design Pattern – Mediator
Simplify the DAO with Spring and Java Generics
Java Program to Compute the Volume of a Tetrahedron Using Determinants
Versioning a REST API
Case-Insensitive String Matching in Java
Java Program to Implement Min Heap
Java Program to Find the Edge Connectivity of a Graph
Java Program to Implement HashMap API
Giới thiệu thư viện Apache Commons Chain
Custom Thread Pools In Java 8 Parallel Streams
Java Program to find the number of occurrences of a given number using Binary Search approach
Adding Parameters to HttpClient Requests
Java Program to Implement Gauss Jordan Elimination
Java Program to add two large numbers using Linked List
Lập trình đa luồng với Callable và Future trong Java
Java Program to Implement Pagoda