Multiplicative order in java

Java Programming Java8Java.Util Package

Following is a Java program which prints the multiplicative order of given numbers.

import java.util.Scanner;

Program

public class MultiplicativeOrder {
   public static int gcd(int num1, int num2) {
      if (num2 != 0) {
         return gcd(num2, num1 % num2);
      } else {
         return num1;
      }
   }
   static int multiplicativeOrder(int num1, int num2) {
      if (gcd(num1, num2) != 1) {
         return -1;
      }
      int res = 1;
      int p = 1;
     
      while (p < num2) {
         res = (res * num1) % num2;
         if (res == 1) {
            return p;
         }
         p++;
      }
      return -1;
   }  
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter number1");
      int num1 = sc.nextInt();
      System.out.println("Enter number2");
      int num2 = sc.nextInt();
      System.out.println(multiplicativeOrder(num1, num2));
   }
}

Output

Enter number1
10
Enter number2
7
Multiplicative order: 6
raja
Updated on 25-Jun-2020 12:39:40

Advertisements