Find the prime factors

23

1

In this task, you have to write a program, that computes the prime factors of a number. The input is a natural number 1 < n < 2^32. The output is a list of the prime factors of the number in the following format. Exponents must be omitted if they are 1. Only output prime numbers. (Assuming the input is 131784):

131784 = 2^3 * 3 * 17^2 * 19

Using the same amount of whitespace is not required; whitespace may be inserted wherever appropriate. Your program should complete in less then 10 minutes for any input. The program with the shortest amount of characters wins.

FUZxxl

Posted 2011-04-06T20:01:14.137

Reputation: 9 656

@IngoBürk I think CJam was invented after this challenge was posted, disqualifying it. – FUZxxl – 2015-02-08T16:06:04.623

@IngoBürk 18 chars: rimF{1-'^*}%" * "* and indeed it doesn't qualify – aditsu quit because SE is EVIL – 2015-02-10T16:14:36.730

9Bonus points if your program can factor 6857599914349403977654744967172758179904114264612947326127169976133296980951450542789808884504301075550786464802304019795402754670660318614966266413770127 in less than 73 days! – Joey Adams – 2011-04-07T02:08:39.683

@Joey Adams: The factorization starts out with 1771113997313597... – FUZxxl – 2011-04-09T15:48:13.550

3

@FUZxxl: I think you made a mistake copying the number. It's the product of two large primes.

– Joey Adams – 2011-04-09T17:50:51.247

@Joey Can we use Shor's Algorithm? – Mateen Ulhaq – 2011-05-03T03:30:28.623

@muntoo: Do you have the hardware to test it? :-) – Joey Adams – 2011-05-03T05:42:59.820

23@Joey I accidentally spilled some coffee over my quantum computer, and my friend is using his to "hack into the US Government" or something unimportant, so, no. :( – Mateen Ulhaq – 2011-05-03T05:59:53.873

What, no CJam yet? – Ingo Bürk – 2014-11-01T07:22:24.173

Answers

11

SageMath, 31 Bytes

N=input()
print N,"=",factor(N)

Test case: 83891573479027823458394579234582347590825792034579235923475902312344444 Outputs:

83891573479027823458394579234582347590825792034579235923475902312344444 = 2^2 * 3^2 * 89395597 * 98966790508447596609239 * 263396636003096040031295425789508274613

12431234123412341234123

Posted 2011-04-06T20:01:14.137

Reputation: 305

Congrats on winning a challenge with your very first post, nice work! And welcome to the site! – James – 2016-09-20T17:10:54.767

8

Ruby 1.9, 74 70 characters

#!ruby -plrmathn
$_+=?=+$_.to_i.prime_division.map{|a|a[0,a[1]]*?^}*?*

Edits:

  • (74 -> 70) Just use the exponent as slice length instead of explicitly checking for exponent > 1

Ventero

Posted 2011-04-06T20:01:14.137

Reputation: 9 842

7

Perl 5.10, 73 88

perl -pe '$_=`factor $_`;s%( \d+)\K\1+%-1-length($&)/length$1%ge;y, -,*^,;s;\D+;=;'

Takes input number from standard input. Will compute factors for multiple inputs if provided.

Counted as a difference to perl -e. 5.10 is needed for the \K regex metacharacter.

J B

Posted 2011-04-06T20:01:14.137

Reputation: 9 638

+1 for using factor. – st0le – 2011-04-07T04:41:55.150

Shouldn't you count the p option? – Joey – 2011-04-07T07:52:52.470

@Joey indeed I should. Sorry about that. Fixing. – J B – 2011-04-07T15:06:04.797

Haven’t tested this, but instead of split/\D/,~factor $_~;$_="@_"; could you write $_=~factor $_~;s/\D/ /g;? (Of course replace ~ with the backtick.) – Timwi – 2011-04-09T00:35:59.357

You mean $_=`factor $_`;s/\D/ /g;? Dual backtick encasing helps. – aaaaaaaaaaaa – 2011-04-09T11:37:45.470

@Timwi it wouldn't have worked because I used split's feature of not yielding a trailing empty string, resulting in the absence of whitespace at end of string. Then again, by not performing the transformation at all, I can keep the newline and have the rest work just fine, so I simplified all that. – J B – 2011-09-08T07:03:29.467

5

Python, 140 135 133 chars

M=N=input()
s=''
f=1
while f<4**8:
 f+=1;e=0
 while N%f<1:e+=1;N/=f
 if e:s+='*%d'%f+'^%d'%e*(e>1)
print M,'=',(s+'*%d'%N*(N>1))[1:]

Keith Randall

Posted 2011-04-06T20:01:14.137

Reputation: 19 865

I think the output requires some more spaces, e.g. ' * %d'... And two more things: 65536 == 4**8; Line 7: if e:s+='*%d'%f+'^%d'%e*(e>1) – Oleh Prypin – 2011-04-07T13:48:01.103

@BlaXpirit: "same amount of whitespace is not required". Thanks for the other two, I'll incorporate them. – Keith Randall – 2011-04-07T16:56:37.623

5

J, 72

(":*/f),'=',([,'*',])/(":"0~.f),.(('^',":)`(''"0)@.(=&1))"0+/(=/~.)f=.q:161784

Typical J. Two characters to do most of the work, sixty characters to present it.

Edit: Fixed the character count.

J B

Posted 2011-04-06T20:01:14.137

Reputation: 9 638

2This doesn't look like 62 characters to me. Even when assuming 161784 is your input, it's still 72 characters. – Ventero – 2011-04-08T16:27:33.103

Wouldn't it be shorter with |: __ q: y? – Eelvex – 2011-04-09T12:24:01.687

2@Ventero: typical JB. Two hours to golf the damned thing, fifteen seconds to mess up the character count. – J B – 2011-04-16T19:41:02.097

5

OCaml, 201 characters

A direct imperative translation of the best Python code:

let(%)s d=if!d>1then Printf.printf"%s%d"s!d
let f n=let x,d,e,s=ref n,ref 1,ref 0,ref"="in""%x;while!d<65536do
incr d;e:=0;while!x mod!d=0do x:=!x/ !d;incr e
done;if!e>0then(!s%d;"^"%e;s:="*")done;!s%x

For example,

# f 4294967292;;
4294967292=2^2*3^2*7*11*31*151*331- : unit = ()

(note that I've omitted outputting the final endline.) Just for fun, at 213 characters, a purely functional version, thoroughly obfuscated through liberal use of operators:

let(%)s d=if d>1then Printf.printf"%s%d"s d
let f x=let s=ref"="in""%x;let rec(@)x d=if d=65536then!s%x else
let rec(^)x e=if x/d*d<x then x,e else x/d^e+1in
let x,e=x^0in if e>0then(!s%d;"^"%e;s:="*");x@d+1in x@2

Matías Giovannini

Posted 2011-04-06T20:01:14.137

Reputation: 281

5

J, 53 52 characters

This solution takes the rplc trick from the solution of randomra but comes up with some original ideas, too.

":,'=',(":@{.,'^','*',~":@#)/.~@q:}:@rplc'^1*';'*'"_

In non-tacit notation, this function becomes

f =: 3 : 0
(": y) , '=' , }: (g/.~ q: y) rplc '^1*' ; '*'
)

where g is defined as

g =: 3 : 0
": {. y) , '^' , (": # y) , '*'
)
  • q: y is the vector of prime factors of y. For instance, q: 60 yields 2 2 3 5.
  • x u/. y applies u to y keyed by x, that is, u is applied to vectors of elements of y for which the entries in x are equal. This is a bit complex to explain, but in the special case y u/. y or u/.~ y, u is applied to each vector of distinct elements in y, where each element is repeated for as often as it appears in y. For instance, </.~ 1 2 1 2 3 1 2 2 3 yields

    ┌─────┬───────┬───┐
    │1 1 1│2 2 2 2│3 3│
    └─────┴───────┴───┘
    
  • # y is the tally of y, that is, the number of items iny.

  • ": y formats y as a string.
  • x , y appends x and y.
  • {. y is the head y, that is, its first item.
  • Thus, (": {. y), '^' , (": # y) , '*' formats a vector of n repetitions of a number k into a string of the form k ^ n *. This phrase in tacit notation is :@{.,'^','*',~":@#, which we pass to the adverb /. described further above.
  • x rplc y is the library function replace characters. y has the form a ; b and every instance of string a in x is replaced by b. x is ravelled (that is, reshaped such that it has rank 1) before operation takes place, which is used here. This code replaces ^1* with * as to comply with the mandated output format.
  • }: y is the curtail of y, that is, all but its last item. This is used to remove the trailing *.

FUZxxl

Posted 2011-04-06T20:01:14.137

Reputation: 9 656

Couldn't you save a lot of work by using __ q:? Try it online!

– Adám – 2017-05-04T10:46:05.307

@Adám Indeed, good idea! – FUZxxl – 2017-05-04T13:12:13.857

4

PHP, 112

echo$n=$_GET[0],'=';$c=0;for($i=2;;){if($n%$i<1){$c++;$n/=$i;}else{if($c){echo"$i^$c*";}$c=0;if(++$i>$n)break;}}

118

echo $n=$_GET[0],'=';for($i=2;;){if(!($n%$i)){++$a[$i];$n/=$i;}else{if($a[$i])echo "$i^$a[$i]*";$i++;if($i>$n)break;}}

zzzzBov

Posted 2011-04-06T20:01:14.137

Reputation: 2 915

3

Python 119 Chars

M=N=input()
i=1
s=""
while N>1:
 i+=1;c=0
 while N%i<1:c+=1;N/=i
 if c:s+=" * %d"%i+['','^%d'%c][c>1]
print M,'=',s[3:]

fR0DDY

Posted 2011-04-06T20:01:14.137

Reputation: 4 337

1That's what I tried first, but it is too slow for big primes, like 4294967291. – Keith Randall – 2011-04-07T05:56:00.733

@Keith The question allows upto 10 minutes. Will this take more than 10 minutes for the worst case? – fR0DDY – 2011-04-07T07:01:17.213

2It took 32 minutes on my machine for that number. – Keith Randall – 2011-04-07T16:54:20.323

3

JavaScript, 124 122 119

for(s='',i=2,o=p=prompt();i<o;i++){for(n=0;!(p%i);n++)p/=i;n?s+=i+(n-1?'^'+n:'')+'*':0}alert(s.substring(0,s.length-1))

Ry-

Posted 2011-04-06T20:01:14.137

Reputation: 5 283

3

Perl, 78

use ntheory":all";say join" * ",map{(join"^",@$_)=~s/\^1$//r}factor_exp(shift)

It uses the s///r feature of Perl 5.14 to elide the ^1s. 81 characters to run in a loop:

perl -Mntheory=:all -nE 'chomp;say join" * ",map{(join"^",@$_)=~s/\^1$//r}factor_exp($_);'

DanaJ

Posted 2011-04-06T20:01:14.137

Reputation: 466

You can leave out the spaces if you like. This would save two characters. Nice solution! – FUZxxl – 2014-11-01T10:08:24.510

2

Java 10, 109 108 bytes (lambda function) (non-competing on request of OP)

n->{var r=n+"=";for(int i=1,f;i++<n;r+=f<1?"":(f<2?i:i+"^"+f)+(n>1?"*":""))for(f=0;n%i<1;n/=i)f++;return r;}

Try it online.

Java 6+, 181 bytes (full program)

class M{public static void main(String[]a){long n=new Long(a[0]),i=1,f;String r=n+"=";for(;i++<n;r+=f<1?"":(f<2?i:i+"^"+f)+(n>1?"*":""))for(f=0;n%i<1;n/=i)f++;System.out.print(r);}}

Try it online.

-1 byte thanks to @ceilingcat.

Explanation:

n->{                // Method with integer parameter and String return-type
  var r=n+"=";      //  Result-String, starting at the input with an appended "="
  for(int i=1,f;i++<n;
                    //  Loop in the range [2, n]
      r+=           //    After every iteration: append the following to the result-String:
        f<1?        //     If the factor `f` is 0:
         ""         //      Append nothing
        :           //     Else:
         (f<2?      //      If the factor `f` is 1:
           i        //       Append the current prime `i`
          :         //      Else:
           i+"^"+f) //       Append the current prime `i` with it's factor `f`
         +(n>1?     //      And if we're not done yet:
            "*"     //       Also append a "*"
           :        //      Else:
            ""))    //       Append nothing more
    for(f=0;        //   Reset the factor `f` to 0
        n%i<1;      //   Loop as long as `n` is divisible by `i`
      n/=i)         //    Divide `n` by `i`
      f++;          //    Increase the factor `f` by 1
  return r;}        //  Return the result-String

Kevin Cruijssen

Posted 2011-04-06T20:01:14.137

Reputation: 67 575

@ceilingcat Thanks! – Kevin Cruijssen – 2019-05-10T06:29:15.320

Disqualified as Java 10 was created after this task was published. – FUZxxl – 2019-05-13T11:38:54.540

@FUZxxl I've marked the Java 10 lambda as non-competing, and added a Java 6 program, which was released in December 2006.

– Kevin Cruijssen – 2019-05-13T12:01:44.977

Okay, cool. That works for me! – FUZxxl – 2019-05-13T12:14:28.543

2

Japt, 28 27 26 bytes

-1 byte thanks to Shaggy

+'=+Uk ü ®ÊÉ?ZÌ+'^+Zl:ZÃq*

Try it

Oliver

Posted 2011-04-06T20:01:14.137

Reputation: 7 160

Disqualified as your language was created after this task was published. – FUZxxl – 2019-05-13T11:36:39.023

1

@FUZxxl Using a newer language on an older challenge is allowed

– Oliver – 2019-05-13T14:28:57.087

It was not allowed back when the challenge was posted. I consider it to be unfair to amend the rules of a challenge after the challenge has been posted, so languages published after this challenge remain illegal. – FUZxxl – 2019-05-13T14:30:45.470

1@FUZxxl You don't have to accept my answer, but I am allowed to answer it regardless. – Oliver – 2019-05-13T14:31:45.227

indeed you are! – FUZxxl – 2019-05-13T15:18:42.073

124 bytes – Shaggy – 2019-05-14T16:56:32.410

Wait, crap, no; that'll fail for the likes of 2048. – Shaggy – 2019-05-14T17:58:13.453

2

PHP, 236 characters

$f[$n=$c=$argv[1]]++;echo"$n=";while($c){$c=0;foreach($f as$k=>$n)for($r=~~($k/2);$r>1;$r--){if($k%$r==0){unset($f[$k]);$f[$r]++;$f[$k/$r]++;$c=1;break;}}}foreach($f as$k=>$n)if(--$n)$f[$k]="$k^".++$n;else$f[$k]=$k;echo implode("*",$f);

Output for 131784: 2^3*3*17^2*19

Completes all numbers within a few seconds while testing.

4294967296=2^32
Time: 0.000168

Input was never specified, so I chose to call it using command line arguments.

php factorize.php 4294967296

Kevin Brown

Posted 2011-04-06T20:01:14.137

Reputation: 5 756

2

Scala 374:

def f(i:Int,c:Int=2):List[Int]=if(i==c)List(i)else 
if(i%c==0)c::f(i/c,c)else f(i,c+1)
val r=f(readInt)
class A(val v:Int,val c:Int,val l:List[(Int,Int)])
def g(a:A,i:Int)=if(a.v==i)new A(a.v,a.c+1,a.l)else new A(i,1,(a.v,a.c)::a.l)
val a=(new A(r.head,1,Nil:List[(Int,Int)])/:(r.tail:+0))((a,i)=>g(a,i))
a.l.map(p=>if(p._2==1)p._1 else p._1+"^"+p._2).mkString("", "*", "")

ungolfed:

def factorize (i: Int, c: Int = 2) : List [Int] = {
  if (i == c) List (i) else 
    if (i % c == 0) c :: f (i/c, c) else 
      f (i, c+1)
}
val r = factorize (readInt)
class A (val value: Int, val count: Int, val list: List [(Int, Int)])
def g (a: A, i: Int) = 
  if (a.value == i) 
    new A (a.value, a.count + 1, a.list) else 
    new A (i, 1, (a.value, a.count) :: a.list)
val a = (new A (r.head, 1, Nil: List[(Int,Int)]) /: (r.tail :+ 0)) ((a, i) => g (a, i))
a.l.map (p => if (p._2 == 1) p._1 else
  p._1 + "^" + p._2).mkString ("", "*", "")

user unknown

Posted 2011-04-06T20:01:14.137

Reputation: 4 210

2

J, 74 chars

f=.3 :0
(":y),'=',' '-.~('^1 ';'')rplc~}:,,&' *'"1(,'^'&,)&":/"{|:__ q:y
)

   f 131784
131784=2^3*3*17^2*19

64 chars with input in variable x:

   x=.131784

   (":x),'=',' '-.~('^1 ';'')rplc~}:,,&' *'"1(,'^'&,)&":/"{|:__ q:x
131784=2^3*3*17^2*19

randomra

Posted 2011-04-06T20:01:14.137

Reputation: 19 909

If you manage to turn this into a tacit definition, you can avoid escaping all the quotes. You could also use a 3 : 0 defintion. – FUZxxl – 2015-02-08T15:53:13.263

@FUZxxl I expected I can just put in the unescaped string in the 3 : 0 version but it didn't work somewhy. I might try tacit later though. This is the 3:0 I tried: http://pastebin.com/rmTVAk4j.

– randomra – 2015-02-08T15:57:57.963

It should work. I don't see why. Did you name your argument y as you are supposed to? – FUZxxl – 2015-02-08T15:59:56.873

@FUZxxl This is the 3:0 I tried: http://pastebin.com/rmTVAk4j.

– randomra – 2015-02-08T16:00:32.110

The 3:0 you tried doesn't exactly match the one-liner you provide. It uses '' instead of a: in one place. Maybe that's the difference? – FUZxxl – 2015-02-08T16:04:47.163

@FUZxxl I just changed '' to a: to decrease escaping. – randomra – 2015-02-08T16:06:34.733

I tried this and it worked. I don't know where your problem is.

– FUZxxl – 2015-02-08T16:07:13.577

@FUZxxl Thanks, now it works. No idea what was the problem. – randomra – 2015-02-08T16:21:15.907

Thank you for the rplc trick. I incorporated it into my solution.

– FUZxxl – 2015-02-08T17:21:08.373

Couldn't you save a lot of work by using __ q:? Try it online!

– Adám – 2017-05-04T10:46:08.820

@Adám that is the first (rightmost) step in the code: ´__ q:x´ – randomra – 2017-05-06T12:59:56.927

1

Powershell, 113 97 bytes

Inspired by Joey's answer. It's a slow but short.

param($x)(2..$x|%{for(;!($x%$_)){$_
$x/=$_}}|group|%{$_.Name+"^"+$_.Count-replace'\^1$'})-join'*'

Explained test script:

$f = {

param($x)               # let $x stores a input number > 0
(2..$x|%{               # loop from 2 to initial input number
    for(;!($x%$_)){     # loop while remainder is 0
        $_              # push a current value to a pipe
        $x/=$_          # let $x is $x/$_ (new $x uses in for condition only)
    }
}|group|%{              # group all values
    $_.Name+"^"+$_.Count-replace'\^1$'  # format and remove last ^1
})-join'*'              # make string with *

}

&$f 2
&$f 126
&$f 129
&$f 86240
#&$f 7775460

Output:

2
2*3^2*7
3*43
2^5*5*7^2*11

mazzy

Posted 2011-04-06T20:01:14.137

Reputation: 4 832

1

05AB1E, 22 20 bytes (non-competing on request of OP)

ÐfsÓ0Køε1K'^ý}'*ý'=ý

-2 bytes thanks to @Emigna.

Try it online.

Explanation:

Ð                # Triplicate the (implicit) input-integer
 f               # Pop and push all prime factors (without counting duplicates)
  s              # Swap to take the input again
   Ó             # Get all prime exponents
    0K           # Remove all 0s from the exponents list
      ø          # Zip it with the prime factors, creating pairs
       ε         # Map each pair to:
        1K       #  Remove all 1s from the pair
        '^ý     '#  And then join by "^"
       }'*ý     '# After the map: join the string/integers by "*"
           '=ý  '# And join the stack by "=" (with the input we triplicated at the start)
                 # (after which the result is output implicitly)

Kevin Cruijssen

Posted 2011-04-06T20:01:14.137

Reputation: 67 575

1K should work instead of `≠iy in the loop. – Emigna – 2019-05-10T08:39:47.530

@Emigna Ah lol.. I actually do that in my Jelly answer I just posted. Not sure why I didn't think of it earlier here. :)

– Kevin Cruijssen – 2019-05-10T08:49:27.953

Disqualified as your language was created after this task was published. – FUZxxl – 2019-05-13T11:37:36.310

1

Jelly, 16 bytes (non-competing on request of OP)

³”=³ÆFḟ€1j€”^j”*

One of my first Jelly answers, so can definitely be golfed (especially ³”=³)..

Try it online.

Explanation:

³                 # Push the first argument
 ”=               # Push string "="
   ³ÆF            # Get the prime factor-exponent pairs of the first argument
      ḟ€1         # Remove all 1s from each pair
         j€”^     # Join each pair by "^"
             j”*  # Join the pair of strings by "*"
                  # (implicitly join the entire 'stack' together)
                  # (which is output implicitly as result)

Kevin Cruijssen

Posted 2011-04-06T20:01:14.137

Reputation: 67 575

Disqualified as your language was created after this task was published. – FUZxxl – 2019-05-13T11:38:36.453

@FUZxxl Since mid-2017 non-competing isn't in the meta anymore, unless the challenge explicitly states that languages should be older than the time of posting. But if you as the one who posted the challenge chooses to not allow languages newer than your challenge post-date, I will edit my answers to add the explicit (non-competing). :)

– Kevin Cruijssen – 2019-05-13T11:47:22.740

I believe the site consensus that was in place when this challenge was posted should define the rules for answers. Everything else (i.e. rules that change after the challenge was posted) would be unfair. Please mark your answers as non competing. – FUZxxl – 2019-05-13T11:55:19.933

@FUZxxl I've marked my answers as non-competing, as requested. – Kevin Cruijssen – 2019-05-13T12:02:28.673

Thank you for your help. – FUZxxl – 2019-05-13T12:13:42.727

1

APL(NARS), 66 chars, 132 bytes

{(⍕⍵),'=',3↓∊{m←' * ',⍕↑⍵⋄1=w←2⊃⍵:m⋄m,'^',⍕w}¨v,¨+/¨{k=⍵}¨v←∪k←π⍵}

test and comment:

  f←{(⍕⍵),'=',3↓∊{m←' * ',⍕↑⍵⋄1=w←2⊃⍵:m⋄m,'^',⍕w}¨v,¨+/¨{k=⍵}¨v←∪k←π⍵}
  f 131784
131784=2^3 * 3 * 17^2 * 19
  f 2
2=2
  f (2*32)
4294967296=2^32

{(⍕⍵),'=',3↓∊{m←' * ',⍕↑⍵⋄1=w←2⊃⍵:m⋄m,'^',⍕w}¨v,¨+/¨{k=⍵}¨v←∪k←π⍵}
k←π⍵      find the factors with repetition of ⍵ and assign that array to k example for 12 k is 2 2 3
v←∪       gets from k unique elements and put them in array v
+/¨{k=⍵}¨ for each element of v count how many time it appear in k (it is array exponents)
v,¨       make array of couples from element of v (factors unique) and the array above (exponents unique)
∊{m←' * ',⍕↑⍵⋄1=w←2⊃⍵:m⋄m,'^',⍕w}¨ pretty print the array of couples factor exponent as array chars
3↓                                 but not the first 3 chars
(⍕⍵),'='  but print first the argument and '=' in char format

if someone has many time with these primitives, know them very well them, for me it is possible that the code is clearer of comments... so code more clear than comments, comments unuseful...

RosLuP

Posted 2011-04-06T20:01:14.137

Reputation: 3 036

0

PHP, 112 bytes

<?=$a=$argn,"=";for($i=2;1<$a;)$a%$i?$i++:$a/=$i+!++$r[$i];foreach($r as$k=>$v)echo$t?"*":!++$t,$v<2?$k:"$k^$v";

Try it online!

Jörg Hülsermann

Posted 2011-04-06T20:01:14.137

Reputation: 13 026

0

PHP, 93 bytes

<?=$n=$argn;for($i=2;$n>1;$k&&$p=print($p?"*":"=")."$i^$k",$i++)for($k=0;$n%$i<1;$n/=$i)$k++;

I could do 89 bytes with PHP 5.5 (or later), but that postdates the challenge by more than 2 years:

<?=$n=$argn;for($i=2;$n>1;$k&&$p=print"=*"[$p]."$i^$k",$i++)for($k=0;$n%$i<1;$n/=$i)$k++;

Run as pipe with -nF or try them online.

Titus

Posted 2011-04-06T20:01:14.137

Reputation: 13 814

0

JavaScript, 107

n=prompt()
s=n+'='
c=0
for(i=2;;){if(n%i<1){c++
n/=i}else{if(c)s+=i+'^'+c+'*'
c=0
if(++i>n)break}}
alert(s)

120

n=prompt()
o={2:0}
for(i=2,c=n;i<=c;)!(c%i)?++o[i]?c/=i:0:o[++i]=0
s=n+'='
for(i in o)s+=o[i]?i+'^'+o[i]+'*':''
alert(s)

zzzzBov

Posted 2011-04-06T20:01:14.137

Reputation: 2 915

1Has a trailing * in the output and prints the exponent even if it's 1. – Ventero – 2011-04-09T08:54:50.303

no need to downvote. There's nowhere that said that it couldn't print the exponent if it's 1. Also, the trailing * assumes multiplying by 1. If it's that big an issue, I'll fix it. – zzzzBov – 2011-04-09T17:47:33.050

1»in the following format« in the task description pretty much implies that an exponent of 1 should not be printed. And no, a trailing * is also against that. If one could choose the output format that freely, then shelling out to factor(1) would be the easiest one. Answers can only reasonably compared if they all solve the same problem. – Joey – 2011-04-09T23:13:54.180

3As the creator of this task, I say, that the exponents have to be omitted if 1 and only prime-numbers can be factors. – FUZxxl – 2011-04-10T11:48:50.603