2因素分解


14

给定一个自然数,n编写一个程序或函数,以获取可用于实现的所有可能的两个因子乘法的列表n。为了更好的理解,你可以去什么假装http://factornumber.com/?page=16777216看的时候n16777216我们得到如下列表:

   2 × 8388608  
   4 × 4194304  
   8 × 2097152  
  16 × 1048576  
  32 ×  524288  
  64 ×  262144  
 128 ×  131072  
 256 ×   65536  
 512 ×   32768  
1024 ×   16384
2048 ×    8192
4096 ×    4096

无需在这里打印漂亮的东西。要求是每个条目(一对因素)之间必须很好地区分,并且在每个对内部,第一个因素也必须彼此很好地区分。如果选择返回列表/数组,则内部元素可以是具有两个元素的列表/数组,也可以是支持C ++之类的东西的某种语言结构std::pair

不要打印乘以1的乘积,也不要重复将第一个因数换成第二个因数的项,因为它们几乎没有用。

没有赢家;这将是每个语言的高尔夫代码。


2
您能否添加一个较小的测试用例,例如30
caird coinheringaahing

1
@cairdcoinheringaahing您可以使用factornumber.com生成更多测试用例。
乔纳森·弗雷奇

1
我最近看过这场“每种语言”比赛。重点是什么?根据语言,大多数Q不会超过1或2,并且您仍然只能选择一个A作为正确的语言。
fede s。

5
@fedes。通常是因为在语言之间进行比较没有意义(例如Java与Jelly)。
totallyhuman

1
@totallyhuman是的,我知道。我的大部分答案都在Factor甚至Smalltalk中。没有机会违反高尔夫语言。也许有可能是通过冗长和boilerplatery排名语言的某种方式
FEDE秒。

Answers:


6

Java(OpenJDK 8)81 66 65字节

  • -15字节,感谢OlivierGrégoire。
  • -1字节:++j<=i/j-> j++<i/j
i->{for(int j=1;j++<i/j;)if(i%j<1)System.out.println(j+" "+i/j);}

在线尝试!


旧的(供参考)

Java(OpenJDK 8),126字节

i->{java.util.stream.IntStream.range(2,i).filter(d->d<=i/d&&i%d==0).forEach(e->System.out.println(""+e+"x"+i/e));return null;}

在线尝试!

第一个codegolf提交和第一个lambda用法。未来的自我,请原谅我的代码。


1
不错的入门!欢迎来到PPCG!这是通过删除所有多余的内容将其压缩为66个字节:尽管我不能打高尔夫球。
OlivierGrégoire17年






3

Perl 6、38个字节

{map {$^a,$_/$a},grep $_%%*,2.. .sqrt}

尝试一下

展开:

{   # bare block lambda with implicit parameter 「$_」

  map
    { $^a, $_ / $a },  # map the number with the other factor

    grep
      $_ %% *,         # is the input divisible by *
      2 .. .sqrt       # from 2 to the square root of the input
}

3

Brachylog,8个字节

{~×≜Ċo}ᵘ

在线尝试!

说明

{~×≜Ċo}ᵘ
{     }ᵘ  List the unique outputs of this predicate.
 ~×       Pick a list of integers whose product is the input.
   ≜      Force concrete values for its elements.
    Ċ     Force its length to be 2.
     o    Sort it and output the result.

部分的输出中不包含1,因此对于输入N,它给出的是[N]而不是[1,N],后者随后由剔除Ċ。我不确定为什么需要...


1
是必要的,因为否则没有选择点:一个长度为2的列表,其产品的输入是唯一的答案,如果你不实际要求列表的值。
致命

2

Japt,9字节

â¬Å£[XZo]

在线测试!返回一个数组数组,末尾有一些空值;-R添加了标志以更清楚地显示输出。


1
因此,我认为应该考虑-R的字节数...
sergiol

3
@sergiol,不,在这种情况下,它仅用于格式化输出以提高可读性。
毛茸茸的

确实是我所拥有的解决方案,只不过我null在最后过滤了s。
毛茸茸的

2

果冻,8 字节

½ḊpP⁼¥Ðf

单数链接,获取数字并返回数字列表(对)的列表。

在线尝试!(本16777216示例在TIO上超时,因为它将创建687亿对的列表,并过滤出具有正确产品的对!)

怎么样?

½ḊpP⁼¥Ðf - Link: number, n     e.g. 144
½        - square root of n          12
 Ḋ       - dequeue*                 [2,3,4,5,6,7,8,9,10,11,12]
  p      - Cartesian product**      [[2,1],[2,2],...[2,144],[3,1],...,[3,144],...,[12,144]
      Ðf - filter keep if:
     ¥   -   last two links as a dyad (n is on the right):
   P     -     product
    ⁼    -     equals
         -                          [[2,72],[3,48],[4,36],[6,24],[8,18],[9,16],[12,12]]

* ,出队,在执行操作之前隐式地使数值输入范围,而范围函数隐式地对其输入进行底限运算,因此,例如,n=24结果½4.898...;。范围变为[1,2,3,4]; 并且出队结果是[2,3,4]

**与上面的p笛卡尔乘积相似,它为数字输入确定范围-在这里,正确的自变量n因此是[1,2,3,...,n]在实际的笛卡尔乘积发生之前的正确自变量。


2

外壳,8字节

tüOSze↔Ḋ

在线尝试!

说明

tüOSze↔Ḋ  Implicit input, say n=30.
       Ḋ  List of divisors: [1,2,3,5,6,10,15,30]
      ↔   Reverse: [30,15,10,6,5,3,2,1]
   Sze    Zip with original: [[1,30],[2,15],[3,10],[5,6],[6,5],[10,3],[15,2],[30,1]]
 üO       Deduplicate by sort: [[1,30],[2,15],[3,10],[5,6]]
t         Drop first pair: [[2,15],[3,10],[5,6]]

2

JavaScript(ES6),55个字节

n=>eval('for(k=1,a=[];k*++k<n;n%k||a.push([k,n/k]));a')

演示版

Try It Online!


Is it me or does this fail for 6?
Neil

@Neil "We can fix it." (Thanks for reporting!)
Arnauld

How can I supply a number to test?
sergiol


1

Python 2, 59 bytes

lambda N:{(n,N/n,n)[n>N/n:][:2]for n in range(2,N)if N%n<1}

Try it online!



@sergiol Yes, a MemoryError, since Python tries to evaluate range(2,N) and store it as a list, yet the allocated memory does not suffice. One could try replace range with xrange (Python 2's range generator), though this exceeds TIO's one minute of maximum runtime. On a machine with enough memory and time, this program should terminate and return the correct answer.
Jonathan Frech



1

PHP, 70 bytes

As string (70 bytes):

$i++;while($i++<sqrt($a=$argv[1])){echo !($a%$i)?" {$i}x".($a/$i):'';}

As array dump (71 bytes):

$i++;while($i++<sqrt($a=$argv[1]))!($a%$i)?$b[$i]=$a/$i:'';print_r($b);

(im not sure if i can use return $b; instead of print_r since it no longer outputs the array, otherwise i can save 2 bytes here. )

The array gives the results like:

Array
(
    [2] => 8388608
    [4] => 4194304
    [8] => 2097152
    [16] => 1048576

"If you choose to return a list/array" To me it means you can print or return as you see fit.
fede s.

On second thought, returning should be valid for a function, and printing for a program. You seem to have a snippet/program, not a function, so I'd say in this case you should be printing.
fede s.

1

Jelly, 12 bytes

ÆDµżUḣLHĊ$$Ḋ

Try it online!

How it works

ÆDµżUḣLHĊ$$Ḋ - Main monadic link;
             - Argument: n (integer) e.g. 30
ÆD           - Divisors                   [1, 2, 3, 5, 6, 10, 15, 30]
    U        - Reverse                    [30, 15, 10, 6, 5, 3, 2, 1]
   ż         - Interleave                 [[1, 30], [2, 15], [3, 10], [5, 6], [6, 5], [10, 3], [15, 2], [30, 1]]
         $$  - Last 3 links as a monad
      L      -   Length                   8
       H     -   Halve                    4
        Ċ    -   Ceiling                  4
     ḣ       - Take first elements        [[1, 30], [2, 15], [3, 10], [5, 6]]
           Ḋ - Dequeue                    [[2, 15], [3, 10], [5, 6]]


1

Factor, 58

Well, there has to be some Factor in this question!

[ divisors dup reverse zip dup length 1 + 2 /i head rest ]

It's a quotation. call it with the number on the stack, leaves an assoc (an array of pairs) on the stack.

I'm never sure if all the imports count or not, as they're part of the language. This one uses:

USING: math.prime.factors sequences assocs math ;

(If they count, I should look for a longer solution with shorter imports, which is kind of silly)

As a word:

: 2-factors ( x -- a ) divisors dup reverse zip dup length 1 + 2 /i head rest ;

50 2-factors .
 --> { { 2 25 } { 5 10 } }

1

Ruby, 43 bytes

->n{(2..n**0.5).map{|x|[[x,n/x]][n%x]}-[p]}

Try it online!

How it works:

For every number up to sqrt(n), generate the pair [[x, n/x]], then take the n%xth element of this array. If n%x==0 this is [x, n/x], otherwise it's nil. when done, remove all nil from the list.



0

Husk, 14 12 bytes

tumoOSe`/⁰Ḋ⁰

Try it online!

Explanation

tum(OSe`/⁰)Ḋ⁰  -- input ⁰, eg. 30
           Ḋ⁰  -- divisors [1..⁰]: [1,2,3,5,6,10,15,30]
  m(      )    -- map the following function (example on 10):
     Se        --   create list with 10 and ..
       `/⁰     --   .. flipped division by ⁰ (30/10): [10,3]
    O          --   sort: [3,10]
               -- [[1,30],[2,15],[3,10],[5,6],[5,6],[3,10],[2,15],[1,30]]
 u             -- remove duplicates: [[1,30],[2,15],[3,10],[5,6]]
t              -- tail: [[2,15],[3,10],[5,6]]

0

APL+WIN, 32 bytes

m,[.1]n÷m←(0=m|n)/m←1↓⍳⌊(n←⎕)*.5

Explanation:

(n←⎕) Prompts for screen input

m←(0=m|n)/m←1↓⍳⌊(n←⎕)*.5 Calculates the factors dropping the first

m,[.1]n÷ Identifies the pairs and concatenates into a list.

0

Add++, 18 15 bytes

L,F@pB]dBRBcE#S

Try it online!

How it works

L,   - Create a lambda function
     - Example argument:     30
  F  - Factors;     STACK = [1 2 3 5 6 10 15]
  @  - Reverse;     STACK = [15 10 6 5 3 2 1]
  p  - Pop;         STACK = [15 10 6 5 3 2]
  B] - Wrap;        STACK = [[15 10 6 5 3 2]]
  d  - Duplicate;   STACK = [[15 10 6 5 3 2] [15 10 6 5 3 2]]
  BR - Reverse;     STACK = [[15 10 6 5 3 2] [2 3 5 6 10 15]]
  Bc - Zip;         STACK = [[15 2] [10 3] [6 5] [5 6] [3 10] [2 15]]
  E# - Sort each;   STACK = [[2 15] [3 10] [5 6] [5 6] [3 10] [2 15]]
  S  - Deduplicate; STACK = [[[2 15] [3 10] [5 6]]]



0

Julia 0.6, 41 bytes

~x=[(y,div(x,y))for y=2:x if x%y<1>y^2-x]

Try it online!

Redefines the inbuild unary operator ~ and uses an array comprehension to build the output.

  • div(x,y) is neccessary for integer division. x/y saves 5 bytes but the output is ~4=(2,2.0).
  • Julia allows chaining the comparisons, saving one byte.
  • Looping all the way to x avoids Int(floor(√x)).

0

APL NARS 99 chars

r←f w;i;h
r←⍬⋄i←1⋄→0×⍳0≠⍴⍴w⋄→0×⍳''≡0↑w⋄→0×⍳w≠⌊w⋄→0×⍳w≠+w
A:i+←1⋄→A×⍳∼0=i∣w⋄→0×⍳i>h←w÷i⋄r←r,⊂i h⋄→A

9+46+41+3=99 Test: (where not print nothing, it return something it return ⍬ the list null one has to consider as "no solution")

  f 101    

  f 1 2 3

  f '1'

  f '123'

  f 33 1.23

  f 1.23

  ⎕←⊃f 16777216      
   2 8388608
   4 4194304
   8 2097152
  16 1048576
  32  524288
  64  262144
 128  131072
 256   65536
 512   32768
1024   16384
2048    8192
4096    4096
  f 123
3 41 

0

Pyt, 67 65 bytes

←ĐðĐ0↔/⅟ƖŽĐŁ₂20`ŕ3ȘĐ05Ș↔ŕ↔Đ4Ș⇹3Ș⦋ƥ⇹⁺Ɩ3ȘĐ05Ș↔ŕ↔Đ4Ș⇹3Ș⦋ƤĐ3Ș⁺ƖĐ3Ș<łĉ

I'm pretty sure this can be golfed.

Basically, the algorithm generates a list of all of the divisors of the input (let's call it n), makes the same list, but flipped, interleaves the two (e.g., if n=24, then, at this point, it has [1,24,2,12,3,8,4,6,6,4,8,3,12,2,24,1]), and prints out the elements from index 2 until half the array length, printing each number on a new line, and with an extra new line in between every pair.

Most of the work is done in actually managing the stack.


Saved 2 bytes by using increment function.


0

Perl 5, 50 bytes

sub{map[$_,$_[0]/$_],grep!($_[0]%$_),2..sqrt$_[0]}

Ungolfed:

sub {
    return map  { [$_, $_[0] / $_] }
           grep { !($_[0] % $_) }
           (2 .. sqrt($_[0]));
}

Try it online.

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.