Advertisement
Guest User

Untitled

a guest
Jul 22nd, 2016
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.49 KB | None | 0 0
  1. //https://www.hackerrank.com/challenges/reverse-factorization
  2. import scala.collection.mutable._;
  3. import java.util.Arrays;
  4.  
  5. object Solution {
  6.    
  7.     def main(args: Array[String]) {
  8.         var temp: Array[String] = readLine().split(" ");
  9.         var n: Int = temp(0).toInt;
  10.         var k: Byte = temp(1).toByte;
  11.         var as: Array[Byte] = readLine().split(" ").map((x) => x.toByte);
  12.        
  13.         //Remove nonfactors of n
  14.         //to speed up recursion process
  15.         as = as.filter((x) => n%x == 0);
  16.        
  17.         //Reverse sort array so that
  18.         //first match is smallest set
  19.         Arrays.sort(as);
  20.         as = as.reverse;
  21.        
  22.         var ab: ArrayBuffer[Byte] = new ArrayBuffer[Byte]();
  23.         if (solve(as, 0, n, ab)){
  24.             n = 1;
  25.             ab.append(1);
  26.             for(v <- ab.reverse){
  27.                 n *= v;
  28.                 print(n + " ");
  29.             }
  30.         } else {
  31.             print(-1);
  32.         }
  33.     }
  34.    
  35.     def solve(as: Array[Byte], curI: Byte, curN: Int, factors: ArrayBuffer[Byte]): Boolean = {
  36.         if (curN == 1){
  37.             return true;
  38.         }
  39.         if (curN < 1 || curI >= as.length){
  40.             return false;
  41.         }
  42.         if (curN%as(curI) == 0){
  43.             factors.append(as(curI));
  44.             if (solve(as, curI, curN/as(curI), factors)){
  45.                 return true;
  46.             }
  47.             factors.trimEnd(1);
  48.         }
  49.         return solve(as, (curI+1).toByte, curN, factors);
  50.     }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement