Advertisement
BlackArrow502

Divide it!

Jun 26th, 2019
474
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.27 KB | None | 0 0
  1. package com.company;
  2.  
  3. import java.util.HashMap;
  4. import java.util.Scanner;
  5.  
  6. public class Main {
  7.  
  8.     static HashMap<Long, Long> length = new HashMap<>();
  9.  
  10.  
  11.     public static long divide(long num) {
  12.  
  13.         if (num == 1)
  14.             return 0;
  15.  
  16.         if (length.containsKey(num)) {
  17.             return length.get(num);
  18.         }
  19.  
  20.         if (num % 2 == 0) {
  21.             long temp = divide(num / 2);
  22.             if (temp != -1) {
  23.                 length.put(num, 1 + temp);
  24.                 return 1 + temp;
  25.             }
  26.         }
  27.  
  28.         if (num % 3 == 0) {
  29.             long temp = divide(2 * num / 3);
  30.             if (temp != -1) {
  31.                 length.put(num, 1 + temp);
  32.                 return 1 + temp;
  33.             }
  34.         }
  35.  
  36.         if (num % 5 == 0) {
  37.             long temp = divide(4 * num / 5);
  38.             if (temp != -1) {
  39.                 length.put(num, 1 + temp);
  40.                 return 1 + temp;
  41.             }
  42.         }
  43.  
  44.         length.put(num, -1L);
  45.         return -1;
  46.     }
  47.  
  48.     public static void main(String[] args) {
  49.         Scanner sc = new Scanner(System.in);
  50.  
  51.         int numCases = sc.nextInt();
  52.  
  53.         for (int x = 0; x < numCases; x++) {
  54.             System.out.println(divide(sc.nextLong()));
  55.         }
  56.  
  57.  
  58.     }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement