Product of Digits

Javascript (84 78 76 74 72 70 68)

n=prompt(m="");for(i=9;i-1;)n%i?i--:(m=i+m,n/=i);alert(n-1?-1:m?m:1)

http://jsfiddle.net/D3WgU/7/

Edit: Borrowed input/output idea from other solution, and shorter output logic.

Edit 2: Saved 2 chars by removing unneeded braces in for loop.

Edit 3: Saved 2 chars by rewriting while loop as if statement with i++.

Edit 4: Saved 2 chars by moving around and reducing operations on i.

Edit 5: Convert if statement into ternary format saving 2 more chars.

Edit 6: Save 2 chars by moving i-- into true part of ternary, remove ++i.


Golfscript, 45 43 40 chars

~9{{1$1$%!{\1$/1$}*}12*(}8*>{];-1}*]$1or

Replaces version which didn't group small primes into powers and saves 8 chars while doing so. Note: 12 = floor(9 log 10 / log 5).

Acknowledgements: two characters saved by nicking a trick from @mellamokb; 3 saved with a hint from @Nabb.


JavaScript, 88 72 78 74 69 68

for(s='',i=2,m=n=prompt();i<m;i++)while(!(n%i)){if(i>9){alert(-1);E()}n/=i;s+=i}alert(s)
4 characters longer, but actually an executable script (as opposed to a function).

Edit: Using ideas from the other JavaScript, I can reduce it to this:

for(s='',i=9,n=prompt();i>1;i--)for(;!(n%i);n/=i)s=i+s;alert(n-1?-1:s?s:1)

Finally! A 69-character solution, only uses 1 for loop ;)

for(s='',i=9,n=prompt();i>1;n%i?i--:[n/=i,s=i+s]);alert(n-1?-1:s?s:1)

Okay, shaved off one comma.

for(i=9,n=prompt(s='');i>1;n%i?i--:[n/=i,s=i+s]);alert(n-1?-1:s?s:1)

Tags:

Math

Code Golf