Java Program to Implement Repeated Squaring Algorithm

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.

  1. /**
  2.  ** Java Program to Implement Repeated Squaring Algorithm
  3.  **/
  4.  
  5. import java.util.Scanner;
  6.  
  7. /** Class RepeatedSquaring **/
  8. public class RepeatedSquaring
  9. {
  10.     /** Function for repeated squaring **/
  11.     public double expBySquaring(double x, int n)
  12.     {
  13.         if (n < 0)
  14.             return expBySquaring(1 / x, -n);
  15.         else if (n == 0)
  16.             return 1;
  17.         else if (n == 1)
  18.             return x;
  19.         else if (n % 2 == 0)
  20.             return expBySquaring(x * x, n / 2);
  21.         else 
  22.             return x * expBySquaring(x * x, (n - 1)/2);    
  23.     }
  24.     /** Main function **/
  25.     public static void main (String[] args) 
  26.     {
  27.         Scanner scan = new Scanner(System.in);
  28.         System.out.println("Repeated Squaring Algorithm Test\n");
  29.         /** Make an object of RepeatedSquaring class **/
  30.         RepeatedSquaring rs = new RepeatedSquaring();
  31.  
  32.         /** Accept n , k **/
  33.         System.out.println("\nEnter n and k of (N ^ K)");
  34.         double n = scan.nextDouble();
  35.         int k = scan.nextInt();
  36.         double result = rs.expBySquaring(n, k);
  37.  
  38.         System.out.println("\nResult : "+ result);        
  39.     }
  40. }

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

Sanfoundry Global Education & Learning Series – 1000 Java Programs.

advertisement
advertisement
If you wish to look at all Java Programming examples, go to Java Programs.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.