zoukankan      html  css  js  c++  java
  • Find the smallest number whose digits multiply to a given number n

    Given a number ‘n’, find the smallest number ‘p’ such that if we multiply all digits of ‘p’, we get ‘n’. The result ‘p’ should have minimum two digits.

    Examples:

    Input:  n = 36
    Output: p = 49 
    // Note that 4*9 = 36 and 49 is the smallest such number
    
    Input:  n = 100
    Output: p = 455
    // Note that 4*5*5 = 100 and 455 is the smallest such number
    
    Input: n = 1
    Output:p = 11
    // Note that 1*1 = 1
    
    Input: n = 13
    Output: Not Possible

    For a given n, following are the two cases to be considered.
    Case 1: n < 10 When n is smaller than n, the output is always n+10. For example for n = 7, output is 17. For n = 9, output is 19.

    Case 2: n >= 10 Find all factors of n which are between 2 and 9 (both inclusive). The idea is to start searching from 9 so that the number of digits in result are minimized. For example 9 is preferred over 33 and 8 is preferred over 24.
    Store all found factors in an array. The array would contain digits in non-increasing order, so finally print the array in reverse order.

     1     public static int findSmallest(int n){
     2         if(n < 10) return 10 + n;
     3         int out = 0;
     4         int pos = 0;
     5         for(int i = 9; i > 1; i --){
     6             while(n % i == 0){
     7                 n /= i;
     8                 out += i * Math.pow(10, pos);
     9                 pos ++;
    10             }
    11         }
    12         return n ==1 ? out : -1;
    13     }
  • 相关阅读:
    第 4 章 MySQL 安全管理
    第 3 章 MySQL 存储引擎简介
    第 2 章 MySQL 架构组成
    道教的【五行】学说
    【matlab】MTATLAB解线性方程组
    RPolar项目进度记录
    numpy和TensorFlow的函数
    卷积
    腾讯QQ空间超分辨率技术TSR
    混元桩
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/3847847.html
Copyright © 2011-2022 走看看