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 Suffix Array
Java Program to Implement Gaussian Elimination Algorithm
Java Program to Give an Implementation of the Traditional Chinese Postman Problem
Java Program to Implement Bit Array
Java Program to Find the Number of Ways to Write a Number as the Sum of Numbers Smaller than Itself
Spring 5 Testing with @EnabledIf Annotation
Guide to Escaping Characters in Java RegExps
Convert Hex to ASCII in Java
Assertions in JUnit 4 and JUnit 5
OAuth2.0 and Dynamic Client Registration
Java – Reader to InputStream
Spring Cloud Series – The Gateway Pattern
Converting Iterator to List
Java Program to Generate Random Numbers Using Middle Square Method
Java Program to Implement ArrayBlockingQueue API
Java Program to Represent Graph Using Incidence Matrix
Remove HTML tags from a file to extract only the TEXT
Use Liquibase to Safely Evolve Your Database Schema
Form Validation with AngularJS and Spring MVC
Filtering and Transforming Collections in Guava
Validate email address exists or not by Java Code
Wrapper Classes in Java
Multipart Upload with HttpClient 4
Java Program to Generate N Number of Passwords of Length M Each
Java Program to Find Basis and Dimension of a Matrix
Spring WebClient vs. RestTemplate
Java 9 Stream API Improvements
Guide To CompletableFuture
Spring Boot - Cloud Configuration Server
Custom Error Pages with Spring MVC
Supplier trong Java 8
Returning Custom Status Codes from Spring Controllers