C#,69
x是输入的数字
int i=2;while(x>1)if(x%i++==0){x/=--i;Console.Write(i+(x>1?"x":""));};
使用 includes :
using system;
namespace nameSP
{
class Program
{
static void Main(string[] args)
{
int i=2;while(x>1)if(x%i++==0){x/=--i;Console.Write(i+(x>1?"x":""));};
}
}
}
必填的J答案(2个字符):
q:
ANSI C,79个字符
main(d,i){for(d+=scanf("%d",&i);i>1;i%d?++d:printf("%d%c",d,(i/=d)>1?'x':10));}
main()
会带两个 int
参数? - Chris LutzMathematica(包括括号共计15个字符):
FactorInteger
例子:
FactorInteger[42]
{{2, 1}, {3, 1}, {7, 1}}
factor x
。哇喔,只有6个字符!我太牛了!!1! - JustinPython:使用输入和输出共 77 个字符
d,s,n=2,'',input()
while n>1:
if n%d:d+=1
else:s+='%dx'%d;n/=d
print s[:-1]
Haskell, 53 chars:(包括3个换行符)
a%1=[]
a%n|mod n a<1=a:p(div n a)|1>0=(a+1)%n
p=(2%)
例子:
*Main> p 1806046
[2,11,11,17,439]
Python(不含I/O共228个字符,含I/O共340个字符):
import sys
def primeFactors(n):
l = []
while n > 1:
for i in xrange(2,n+1):
if n % i == 0:
l.append(i)
n = n // i
break
return l if len(l) > 0 else [n]
n = int(sys.argv[1])
print '%d: %s' % (n, 'x'.join(map(lambda x: str(x), primeFactors(n))))
可以压缩到120个字符:
import sys
n,l=int(sys.argv[1]),[]
while n>1:
for i in range(2,n+1):
if n%i==0:l+=[str(i)];n/=i;break
print'x'.join(l)
if
之前有一个制表符,而不是四个空格。它作为另一级缩进工作,只需要一个字符,而不是两个字符的代价。APL中的11个字符
不包括函数头和换行符
factors←{2÷/∪⌽∧\⍵∨⍳⍵}
81 chars
let rec f n=if n=1 then[]else let a=[2..n]|>List.find(fun x->n%x=0)in a::f(n/a)
虽然效率很低,但由于目标无疑是编写尽可能最短的代码,我忽略了这个问题。
可读形式(使用#light
语法):
let rec factorise n =
if n = 1 then [] else
let a = [2 .. n] |> List.find (fun x -> n % x = 0)
a :: factorise (n / a)
GNU bc,包括输入收集的内容在内共 47 个字符(需要 GNU 扩展支持 print
、else
和 read
):
x=read();for(i=2;x>1;)if(x%i){i+=1}else{x/=i;i}
x=read();for(i=2;x>1;)if(x%i){i+=1}else{x/=i;print i;if(x>1)"x"}