Find the smallest number whose digits multiply to a given number n

Source: Internet
Author: User

Given a number 'n', find the smallest number 'P' such that if we multiply all digits of 'P', we get 'n '. the result 'P' shoshould have minimum two digits.

Examples:

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

For a given n, following are the two cases to be considered.
Case 1: n <10When 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> = 10Find all factors of n which are between 2 and 9 (both transaction SIVE ). 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 wocould 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     }

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.