打印两个数字的最大公因数的素数分解


17

标题说明了一切。两个输入的32位正整数m, n >= 2gcd(m,n)以素数分解形式输出。

输入值

命令行参数或1行stdin可以,对于高尔夫来说更合适。

输出量

用指数分隔的单个空格(没有其他空格)。如果输入是相对质数,则什么也不输出。

例子:

$ ./factorize 96 162
2^1 3^1

$ ./factorize 14 15


$ ./factorize 196 294
2^1 7^2

规则

  • 您不得将外部资源,数学库或内置函数用于分解或GCD。示例:Java,否java.lang.Math。红宝石,否prime_division,perl,否factor

1
如果要寻找什么输出gcd(n,m) == 1
地下

我可以例外退出吗?这样可以节省一些字节。
地下

实际上,我已经改变了方法,没有必要退出。但是其他人可能想知道。
地下

请勿异常退出。什么也没输出:)
durron597

从技术上讲,q:a+.b或者__ q:a+.b在J中使用no external resources or math libraries,但我不会发布它,因为它与问题的精神相去甚远。我只是想在这里分享。
ɐɔıʇǝɥʇuʎs

Answers:


10

Python 3中,255 250 237 226 188 180 150 142 137 136个字符

a,b=map(int,input().split())
t,g='',1
while g<a:
 g,p=g+1,0
 if a%g+b%g<1:
  while a%g+b%g<1:a/=g;b/=g;p+=1
  t+='%d^%d '%(g,p)
print(t)

我可以通过跳过一些东西(例如,找到gcd)来缩短此时间,这真是令人惊讶!另外,我可以通过使该函数期望2个整数(类似于其他答案)来减少10个字符,而不是从stdin中读取。


这太激烈了!通过观看您的编辑并试图击败您,我学到了很多东西。我认为您可能有一个(在Python答案之外)
Rainbolt 2014年

1
通过更改while g<a and g<b:while(g<a)*(g<b):
Rainbolt

@Rusher谢谢队友!您的回答是激励我更加努力地工作的一种方法:)另外,您推荐的技巧也启发了我找出一a%g+b%g点点
塔尔(Tal)2014年

我认为else子句不是必需的。else:g+=1可能只是g+=1,除非我错过了一些东西。
isaacg 2014年

@isaacg您似乎是正确的,谢谢!
2014年

8

红宝石- 168 117 114 101 100 97

编辑:考虑之后,意识到我不需要筛子,因为因子的原始性在分解循环中得到了照顾。另外,根据其他人的回答(虽然我也曾经看到过laindirTal,尽管看起来其他人也这样做),但删除了单独的gcd计算,因为这也发生在因式分解中。
编辑2:不需要do
编辑3:进一步压缩它。
编辑4:再拉出一个空间。
编辑5:upto代替each; ?^ == "^"

a,b=ARGV.map{|i|i.to_i}
2.upto(a){|d|c=0
[c+=1,a/=d,b/=d]while a%d+b%d<1
print d,?^,c," "if c>0}

输出(编辑后相同):

$ ruby factorize.rb 96 162
2^1 3^1 
$ ruby factorize.rb 14 15

$ ruby factorize.rb 196 294
2^1 7^2 

当然可以做得更好,但对于我的第一个来说还不错。


您可以通过更改map{|i|i.to_i}为删除4个字节map &:to_i。您可以通过不计算文件末尾的换行符来删除第5个字节;Ruby没有它就可以工作。
kernigh 2014年

另外,您可以使用$*代替ARGV
daniero 2014年

6

蟒2 - 254 252 196 185 156 151 134 126 121

i=1
a,b=map(int,raw_input().split())
while b:a,b=b,a%b
while~-a:
 i+=1;j=0
 while a%i<1:j+=1;a/=i
 if j:print`i`+'^'+`j`,

口译员

代表

输入示例-stdin

100 50

示例输出-stdout

2 ^ 1 5 ^ 2


1
…`a`+'^'+`f.count(a)`…
Ry-

很干净,我喜欢
qwr

@qwr谢谢。我希望我能理解其他Python答案的String格式并剃一些字符。
Rainbolt 2014年

交换f.append(i)用于f+=[i]保存5个字符。
Nolen皇族2014年

1
现在,您根本不需要使用f:p(为什么f=''还在那里?)
Nolen Royalty

4

爪哇- 184 175

这是受@Geobits(以及@Tal的一些答案)答案的启发,但是我决定创建自己的答案就足够了。

class G{public static void main(String[]a){for(Integer i=1,q,n=i.valueOf(a[0]),m=i.valueOf(a[1]);m>=++i;System.out.print(q>0?i+"^"+q+" ":""))for(q=0;n%i+m%i<1;n/=i,m/=i)q++;}}

带有(人工验证)测试工具的无用(多种):

class G {
    public static void mainMethod(String[] a) {
        for (Integer i = 1, q, n = i.valueOf(a[0]), m = i.valueOf(a[1]); m >= ++i;
                 System.out.print(q > 0 ? i + "^" + q + " " : ""))
            for (q = 0; n % i + m % i < 1; n /= i, m /= i)
                q++;
    }

    public static void main(String[] a) {
        m(3, 3);
        m(196, 294);
        m(294, 196);
        m(14, 15);
        m(15, 14);
        m(96, 162);
        m(162, 96);
        m(300, 400);
        m(400, 300);
        m(100, 100);
        m(7, 7);
        m(4, 8);
    }

    public static void m(int one, int two) {
        mainMethod(new String[] { String.valueOf(one), String.valueOf(two) });
        System.out.println();
    }
}

4

dc,96位元组

?sbsa2sf[q]sk[lalf~lblf~szrlz+0<ksbsale1+selsx]ss[lfn[^]Plen[ ]P]sp[0selsxle0<plf1+dsflb!<w]dswx

它读取一行标准输入。它的输出不以换行符结尾。(编辑:每次分解后,它也会输出额外的空间。其他一些答案会修剪空间,但是这个不会。)

例:

$ echo 301343045 421880263 | dc factorize.dc
1021^1 59029^1 $ 

带有注释的代码:

# dc(1) is a stack language, like Forth. Programs push values on the
# stack, then operate on them. For example, to calculate
#  (2 + 3) * (9 - 4)
# the dc code is
#  [2 3 + 9 4 - *]

# [?] reads a line of input.  We expect two integers >= 2.
# [sb sa] stores the integers in variables.
? sb sa     # a, b = two integers from input

# This program sucks common factors from a and b, looping for
# f = 2, 3, 4, 5, and so on.  This method only sucks prime factors,
# but wastes time when f is not prime.
2 sf        # f = 2

# Code in [...] does not run until the program calls it.

# k = code to break a loop
[
 q           # [q] breaks two levels of [...]
] sk        # k = break

# s = loop to suck factor f from a and b
#  This loop increments e, the exponent for factor f.
#  Please set e = 0 before entering this loop.
[
 # [la lf] puts ( a f ) on the stack.
 # [~] does division and remainder.
             # STACK:
 la lf ~     # ( a/f a%f )
 lb lf ~     # ( a/f a%f b/f b%f )

 # [r] swaps the top two stack values.
 # Hold z = b%f and swap a%f with b/f.
             # STACK:
 sz r lz     # ( a/f b/f a%f b%f )

 # f is a common factor if a%f and b%f are zero.  Because a and b are
 # non-negative, a%f and b%f are zero only if a%f+b%f is zero.
             # STACK:
 +           # ( a/f b/f a%f+b%f )

 # Call k to break loop unless a%f+b%f is zero.  [<k] conditionally
 # calls k if the comparison is true.  Comparisons in dc are
 # backwards, so [3 0 <k] would check 0 < 3.  Because a%f+b%f is never
 # negative, [0 <k] is golf for [0 !=k].
             # STACK:
 0 <k        # ( a/f b/f )

 # f is a common factor, so suck it!
 sb sa       # a = a/f, b = b/f, STACK: ( )
 le 1 + se   # increment e, the exponent for this factor
 ls x        # continue loop, [x] executes s
] ss        # s = loop

# p = code to print "f^e "
[
 # [n] prints a number without a newline.
 # [P] prints a string.
 lf n [^]P
 le n [ ]P

 # DEBUG: Uncomment to print a and b.
 #[(a = ]P la n [, b = ]P lb n [)]P 10P
] sp        # p = print

# w = loop to iterate factors
[
 # Call s loop to suck factor f from a and b, and set exponent e.
 0 se        # e = 0
 ls x        # call s loop

 # DEBUG: Uncomment [c] to clear the stack.  Loop s leaves two junk
 # values ( a/f b/f ) on the stack.  Deleting [c] for code golf saves
 # 1 byte but leaks junk on the stack.
 #c

 # Print "f^e " if 0 < e.  Comparisons in dc are backwards, so
 # [0 le <p] would check e < 0, [le 0 <p] checks 0 < e.
 le 0 <p

 # Increment f.  [d] duplicates top value on stack.
             # STACK:
 lf 1 +      # ( f+1 )
 d           # ( f+1 f+1 )
 sf          # ( f ) as f+1 becomes f

 # Continue loop if b >= f.  This is golf for f <= a and f <= b, as
 # extra iterations of the loop cause no harm.
             # STACK:
 lb          # ( f b )
 !<w         # ( ), continue loop if not b < f
] d sw      # w = loop; STACK: ( w )
x           # enter loop unconditionally; STACK: ( ) at entrance

3

PowerShell-82

$a,$b=$args
2..$a|%{$p=0;while(!($a%$_+$b%$_)){$a/=$_;$b/=$_;$p++}if($p){"$_^$p"}}

这是一个简短易懂的文章。它将范围2..$a传递到Foreach-Object循环中%{...}。循环收集的值if($p){"$_^$p"}
kernigh 2014年

3

JavaScript(ECMAScript 6草案)-89个字符

f=(m,n,i=2,k=0)=>(m%i|n%i?(k?i+'^'+k+' ':'')+(i>m?'':f(m,n,i+1)):f(m/i,n/i,i,k+1)).trim()

将下面的原始(迭代)答案转换为递归答案。

说明

f=(m,n,i=2,k=0)=>           // A function with arguments m and n and optional arguments
                            // i (defaults to 2) and k (defaults to 0)
  (
    m%i|n%i                 // if i is not a divisor of m or n then:
      ?(k?i+'^'+k+' '       //   if k is non-zero append  "i^k " to the output
         :'')               //   else append nothing
        +(i>m?''            //   if i>m then terminate
             :f(m,n,i+1))   //   else increment i and reset k to 0
      :f(m/i,n/i,i,k+1)     // else divide m and n by i and increment k
  ).trim()                  // finally strip any extra spaces from the output.

迭代答案:JavaScript(ECMASCript 6)-108 (或121) 98个字符

版本2:

f=(m,n)=>{for(s='',i=1;++i<=m;s+=k?' '+i+'^'+k:'')for(k=0;m%i+n%i<1;k++)m/=i,n/=i;return s.trim()}

版本1:

回答最初提出的问题:

f=(m,n)=>{for(o=[],i=2;i<=m;)m%i|n%i?i++:(m/=i,n/=i,o[i]=(o[i]|0)+1);return o.map((x,i)=>i+"^"+x).join(' ')}

还是要遵守规则更改后的事实:

f=(m,n)=>{for(o=[],i=2;i<=m;)m%i|n%i?i++:(m/=i,n/=i,o[i]=(o[i]|0)+1);return o.map((x,i)=>i+"^"+x).filter(x=>x).join(' ')}

说明

f=(m,n)=>                        // Create a function f with arguments m and n
{
  o=[]                           // Initialise an empty array for the output
  i=2                            // Start with a divisor of 2
  for(;i<=m;)                    // Loop while the divisor is not greater than m
    m%i|n%i                      // Test the bitwise OR of m%i and n%1 (i.e. whether
                                 // at least one is non-zero)
      ?i++                       // If m%i>0 or n%i>0 then increment i
      :(m/=i,                    // Otherwise: divide m by i;
        n/=i,                    //                   n by i;
        o[i]=(o[i]|0)+1);        // and add 1 to the i-th element of o
  return o.map((x,i)=>i+"^"+x)   // finally map the sparse array o to a sparse array
                                 // of the strings (index+"^"+value)
          .filter(x=>x)          // turn sparse array into non-sparse array
          .join(' ')             // then concatenate and return.
}

输出量

f(96,162)
"2^1 3^1"

f(14,15)
""

f(80, 80)
"2^4 5^1"

f(196,294)
"2^1 7^2"

嘿,你可以试着f(158,237)
durron597

它是用指数分隔的空间(恰好有很多空间)" 79^1"
MT0 2014年

是的,其他解决方案都没有,示例也没有。请修正:)
durron597

正如最初所问的,问题中没有任何内容定义允许或不允许多少空格-正如我所看到的,这满足了要求,因为它是用指数分隔的空格。但是,您现在要去更改规则,不是吗?
MT0

2
根据先前存在的规则,可以说这种实现忽略了“如果输入是相对质数则不输出任何内容”的要求。污蔑这么漂亮的高尔夫球代码似乎仍然是错误的。您能打filter()几小时?
敏锐

3

Perl 6:90个字符,94个字节

sub MAIN(*@n){@n.any%$_||(my$p=$p⊎$_;@n»/=»$_;redo)for
2..@n[0];$p.pairs.fmt("%d^%d").say}

有点偏离高尔夫和评论:

sub MAIN (*@n) { # accept any number of input numbers as @n
    (
        # $p is a Bag, e.g., it holds the primes and the number of times each was added
        my $p = $p ⊎ $_; # Add the prime to the bag
        @n »/=» $_; # Divide all the input numbers by the prime

        redo # Redo the loop iteration with the same prime, in case
             # the numbers can be divided by it multiple times
    )
    if @n.all %% $_ # Do the above only if all of @n are divisible by $_
    for 2..@n[0];   # Do the above for all numbers from 2 .. @n[0]

    $p.pairs.fmt("%d^%d").say # Print join " ", "$prime^$count"
}

用法就像:

$ perl6 -e'sub MAIN(*@n){@n.any%$_||(my$p=$p⊎$_;@n»/=»$_;redo)for
2..@n[0];$p.pairs.fmt("%d^%d").say}' 51 153
3^1 17^1

per是perl中的符号吗?我不知道
durron597 2014年

@ durron597只有Perl 6 :)
Mouq 2014年

3

Perl,144 133 118 114 97 93

($a,$b)=<>=~/\d+/g;for(2..$a){for($n=0;$a%$_+$b%$_<1;$n++,$a/=$_,$b/=$_){}$n&&print"$_^$n ";}

非高尔夫版本:

($a,$b)=<>=~/\d+/g;
for(2..$a){
    for($n=0 ; $a%$_+$b%$_<1 ; $n++,$a/=$_,$b/=$_) {}
    $n&&print"$_^$n ";
}

我刚刚开始学习Perl只是为了回答这个问题(这是我有史以来的第一个Perl代码),因此我怀疑这可以进一步深入研究。


是的,我没有仔细研究过您的代码,但在Perl 5中foreach始终是同义的for,因此应减少4个字符:)
Mouq 2014年

@Mouq我从未见过如此冗余的语言...谢谢:)
Tal

2

Java的:247 241

跟踪数组中的因子,然后将它们循环打印出来。

看起来Java大小合适。

class G{public static void main(String[]a){Integer i=1;int n=i.valueOf(a[0]),m=i.valueOf(a[1]),f[]=new int[n>m?n:m+1];for(;m>=++i||n>i;){if(n%i+m%i<1){f[i]++;n/=i;m/=i--;}}for(i=2;i<f.length;System.out.print(f[i]>0?i+"^"+f[i]+" ":""),i++);}}

// line breaks below

class G{
    public static void main(String[]a){
        Integer i=1;int n=i.valueOf(a[0]),m=i.valueOf(a[1]),f[]=new int[n>m?n:m+1];
        for(;m>=++i||n>i;){
            if(n%i+m%i<1){
                f[i]++;n/=i;m/=i--;
            }
        }
        for(i=1;i<f.length;System.out.print(f[i]>0?i+"^"+f[i]+" ":""),i++);
    }
}

实际上,您可以将其他变量保留为int,您将4输给,int 但是使用new int[->将其重新获得,new Integer[所以很容易。
durron597 2014年

是的,切换n%i<1&&m%i<1到,我又得到了三个n%i+m%i<1
Geobits,2014年

您不需要()。如果为n==m,则默认为默认值m+1
Geobits 2014年

2
您可以替换m/=i;i=1;m/=i--;它也会运行得更快:)
durron597

1
在第一个for循环之后是否需要大括号?
Ypnypn 2014年

2

的JavaScript(ECMAScript的5)170 164 163 113

我几乎无法抗拒跟随MT0的领先。我以前曾考虑过递归,但似乎太容易搞砸了。确实是。丝毫变化会破坏一切。

对于喜欢小提琴的人来说,有个小提琴。

function f(a,b,i,e){return i?a%i|b%i?(e?i+'^'+e+' ':'')+(i>a?'':f(a,b,i+1,0)):f(a/i,b/i,i,e+1):f(a,b,2,0).trim()}

取消高尔夫:

function f(a,b,i,e){
    return i // Check for factor.
        ?a%i|b%i // Check for indivisibility.
            ?(
                e // Check for exponent.
                    ?i+'^'+e+' ' // Add the current factor to result string.
                    :'' // Omit the current non-factor.
             )+(
                i>a // Check for termination state.
                    ?'' // Stop recursion.
                    :f(a,b,i+1,0) // Go to the next factor.
            )
            :f(a/i,b/i,i,e+1) // Failed indivisibility check. Increment exponent and divide subject values.
        :f(a,b,2,0) // Add default factor and exponent.
        .trim() // Get rid of one extra space that's usually on the end.
}

旧版本

function f(a,b){for(var r=[],j=-1,i=2;i<=a;)a%i|b%i?++i:(r[j]&&r[j][0]==i?r[j][1]++:r[++j]=[i,1],a/=i,b/=i);for(j=0;i=r[j];++j)r[j]=i.join('^');return r.join(' ')}

取消高尔夫:

function f(a,b){
    for(var r=[],j=-1,i=2;i<=a;)
        // We (mis)use conditional expression `?:` instead of `if(){}else{}`.
        a%i|b%i ? // Bitwise OR saves one character over logical OR, where applicable.
             // In the truth case, `i` has become uninteresting. Just move on.
            ++i : // We don't mind hitting composites because their prime factors have already been drained from `a` and `b`.
            (
                r[j]&&r[j][0]==i ? // Check if `i` is already a listed factor.
                    r[j][1]++ : // Increment the exponent count.
                    r[++j]=[i,1], // Otherwise, add a new factor with exponent 1.

                a/=i,b/=i // Drain a used-up factor from `a` and `b`.
            );

    // The real work's done. Now we just format.
    for(j=0; i=r[j]; ++j)
        r[j]=i.join('^'); // Join each factor to its exponent.

    return r.join(' ') // Join all factors into result string.
}

以下是一些测试:

[
    f(4, 12),
    f(80, 80),
    f(96,162),
    f(196,294)
];

此递归函数失败,f(301343045, 421880263);可能是因为我的浏览器无法让我递归那么深。笨坏了的Firefox!
kernigh 2014年

当然。在实践中,仅在确实需要某种堆栈(例如用于树导航或其他固有的递归数据结构)的情况下,才使用递归函数。(当然,可以将数字视为递归数据结构,但是我们有各种不错的抽象可以帮助我们忽略这一事实。)
Keen 2014年

2

GolfScript,68个字节

~..),2>*${1$1$%3$2$%+!{.@@/@2$/.}*;}/;;]:D.&{`.[~]D\/,(`"^"\++}%" "*

注意,该方法需要O(b 2)的时间和空间用于整数“ a”和“ b”。

以一个额外的字节为代价,“仅” O(b)的时间和空间是必需的:

~.),2>31*${1$1$%3$2$%+!{.@@/@2$/.}*;}/;;]:D.&{`.[~]D\/,(`"^"\++}%" "*

怎么运行的

~.        # Interpret the input string (“a” and “b”) and duplicate “b”.
.),2>     # Push the array [ 2 3 4 ... b ].
*$        # Repeat each element b times and sort: [ 2 ... 2 3 ... 3 ... b ... b ]
{         # For each element “d” of the array:
  1$1$%   # Calculate a % d.
  3$2$%   # Calculate b % d.
  +!      # Add and negate.
  {       # If both “a” and “b” are divisible by “d”:
    .@@/  # Calculate a / d.
    @2$/  # Calculate b / d.
    .     # Create a dummy value.
  }*      #
  ;       # Pop the topmost stack element (non-divisor “d” or dummy value).
}/        #
;;]       # Pop “a” and “b” and collect the remaining stack elements in an array.
:|.&      # Save that array in “D” and intersect it with itself to deduplicate it.
{         # For each element “d” of “D”:
  `.[~]   # Push string "d" and array [d].
  D\/,(`  # Split “D” around [d] and take the length minus 1. This count the occurrences.
  "^"\    # Push the string "^" and swap it between "d" and it's number of occurrences.
  ++      # Concatenate the three strings.
}%        # Collect all strings into an array.
]" "*     # Join by spaces.

1

Python 3(123)

这使用与Tal的答案基本相同的结构。

a,b=map(int,input().split())
s='';p=1
while p<a:
 c=0;p+=1
 while a%p+b%p<1:a/=p;b/=p;c+=1
 if c:s+='%d^%d '%(p,c)
print(s)

循环到p = a-1就足够了,因为我们立即增加以获得p = a和a> = min(a,b)。如果b> a,则尝试在a之上使用无用的p值没有害处。

在2.X中,我认为我们可以通过在获取时打印每段内容来节省字符,而不必累积字符串:if c:print'%d^%d'%(p,c),。不幸的是,如果没有尾随换行符,Python 3似乎没有紧凑的打印方式。


1

PHP,96

<?php
list(,$a,$b)=$argv;for($s=1;$s++<$a;$c&&print"$s^$c ")for($c=0;1>$a%$s+$b%$s;$a/=$s,$b/=$s)$c++;

我们得到几乎完全相同的代码!我的一项改进是p=0;g+=1g1 开始改为合并成一行,这样您就可以做g<a而不是g<=a。希望您成长为喜欢python的人。
xnor

@xnor我错过了您的代码。确实几乎是一样的。我删除了我的python脚本。我希望我不必喜欢python,我需要大括号
mleko 2014年

无需删除代码,您自己编写了代码。我还提出了基本上是Tal的游戏规则,因此看起来这就是Python高尔夫球融合的目标。
xnor 2014年

1

awk- 115 111 96 85

新版本只能处理一行输入。感谢durron597指出我只需要确定即可i <= $1

{for(i=1;++i<=$1;)for(;$1%i+$2%i==0;f[i]++){$1/=i;$2/=i}$0=z;for(i in f)$i=i"^"f[i]}1

取消高尔夫:

{
    #skip finding gcd as a separate step, get it from the factors
    for(i = 1; ++i <= $1;) {
        for(;$1 % i == 0 && $2 % i == 0; f[i]++) {
            $1 /= i;
            $2 /= i;
        }
    }
    $0 = "";
    for(i in f) {
        $i = i "^" f[i];
    }
    print;
}

以前可以反复取双数字

{a=$1;b=$2;for($0=c;a-b;)if(a>b)a-=b;else b-=a;for(i=2;i<=a;i++){for(j=0;a%i==0;j++)a/=i;$0=$0(j?i"^"j" ":c)}}1

取消高尔夫:

{
    a = $1;
    b = $2;
    $0 = "";
    #rip off Euclid
    for(; a != b;) {
        if(a > b) {
            a = a - b;
        } else {
            b = b - a;
        }
    }
    #but not Eratosthenes
    for(i = 2; i <= a; i++) {
        for(j = 0; a % i == 0; j++) {
            a /= i;
        }
        $0 = $0 (j ? i "^" j " " : "");
    }
    print;
}

需要&&i<=b
durron597 2014年

好吧,我会...你是对的,你不是:if i > b,然后b % i != 0...谢谢:)
laindir

该程序不适用于OpenBSD 5.5中的awk,因为NF=0;无法删除$ 1和$ 2。输出echo 301343045 421880263 | awk -f factorize.awk | sed 's/ */ /g'5 7 1021^1 59029^1因为$ 1为5,$ 2为7。sed压缩了打印$ 1022,$ 1023,$ 1024,...,$ 59028的多余空格,这些空格由空格连接。
kernigh 2014年

感谢@kernigh,它可以在nawk,mawk和gawk中工作。仔细检查了posix关于分配给NF并没有说什么,$0=z;
而是

@laindir所做的更改为我修复了该程序。高尔夫代码不需要程序可移植。幸运的$0=z;是,字符数与相同NF=0;。如果$0=z;更长,我会告诉你保留NF=0;
kernigh 2014年

1

,41字节

这不是竞争性的答案,因为语言比问题新颖。但是,GolfScript的68分需要降低。

Fi2,++a{p:0T$|g%i{++pg/:i}Ipx.:i.'^.p.s}x

输出在空格处结束;如果存在问题,则以下版本也是41个字节(包括-s标志):

Fi2,++a{p:0T$|g%i{++pg/:i}IplAE:i.'^.p}l

格式化,并附有解释:

F i 2,++a {      For i in range(2,a+1); note ++ used to avoid parentheses in 2,(a+1)
  p:0            p will store the greatest power of i that divides both numbers
  T $+(g%i) {    Loop till the sum of g%i is nonzero, where g is a list initialized
                  from cmdline args
    ++p          As long as g%i is [0 0], increment p...
    g/:i         ...and divide both numbers in g by i
  }
  I p            If p is nonzero, i went into both numbers at least once
    x.:i.'^.p.s  Append i^p and a space to the result
}
x                Print the result

点子,与GolfScript,CJam等人不同。是带有中缀运算符的命令式语言;它也从数组编程语言中获得了一些启发。该任务很好地显示了工作中的两个范例。

(请注意,运行此操作需要2015-4-20提交,因为我刚刚修复了两个错误。)


0

Python 2-262字节

n,m=input(),input()
f=lambda i:set(filter(lambda x:i%x<1,range(1,i+1)))
g=max(f(n)&f(m))
p=[]
while g-1:
 p+=[min(filter(lambda x:x>1 and x%2!=(x==2)and not any(map(lambda y:x%y<1,range(2,x))),f(g)))]
 g/=p[-1]
print ' '.join(`a`+^+`p.count(a)`for a in set(p))

6号线需要工作。


1
…`a`+'^'+`f.count(a)`…
Ry-

我不知道我怎么想念它。真是的 谢谢。
Undergroundmonorail

0

Groovy:174个字符

这是Geobits针对Groovy 2.2.1 的解决方案的一部分

int i=1, n=args[0]as int, m=args[1]as int;s=n>m?n:m+1;f=new int[s];while(m>=++i||n>i){if(n%i+m%i<1){f[i]++;n/=i;m/=i--;}};(s-1).times{y=it+1;x=f[y];print"${x>0?"$y^$x ":""}"}

这是非高尔夫版本:

int i = 1, n = args[0] as int, m = args[1] as int

s = n>m?n:m+1
f = new int[s]

while (m>=++i||n>i) {
    if (n%i+m%i<1) {
        f[i]++;n/=i;m/=i--;
    }
}
(s-1).times {
    y=it+1
    x=f[y]
    print"${x>0?"$y^$x ":""}"
}

感到惊讶的是您选择移植Geobits的解决方案而不是我的解决方案,因为我的解决方案要短56个字符
durron597

0

R:139

a=scan();q=1:a[1];n=max(q[!a[1]%%q&!a[2]%%q]);m=rep(0,n);for(i in 2:n){while(!n%%i){m[i]=m[i]+1;n=n/i};if(m[i])cat(paste0(i,"^",m[i])," ")}

缩进:

a=scan() #Take space-separated numeric input from stdin
q=1:a[1]
n=max(q[!a[1]%%q&!a[2]%%q]) #gcd
m=rep(0,n)
for(i in 2:n){
    while(!n%%i){ #prime factorization
        m[i]=m[i]+1
        n=n/i
        }
    if(m[i])cat(paste0(i,"^",m[i])," ")
    }

用法:

> a=scan();q=1:a[1];n=max(q[!a[1]%%q&!a[2]%%q]);m=rep(0,n);for(i in 2:n){while(!n%%i){m[i]=m[i]+1;n=n/i};if(m[i])cat(paste0(i,"^",m[i])," ")}
1: 196 294
3: 
Read 2 items
2^1  7^2  
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.