2 요인 분해


14

자연수가 주어지면 n달성 할 수있는 가능한 두 가지 요소 곱셈의 목록을 얻기위한 프로그램이나 함수를 작성하십시오 n. 당신이 갈 수있는 척한다 더 잘 이해하려면 http://factornumber.com/?page=16777216 때 볼 수 n있다 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

여기 같은 것들을 예쁘게 인쇄 할 필요가 없습니다. 요구 사항은 각 항목 (요인 쌍)이 서로 잘 구분되고 각 쌍 내부에서 첫 번째 요인도 서로 잘 구분되어야한다는 것입니다. 목록 / 배열을 반환하도록 선택하면 내부 요소는 두 요소가있는 목록 / 배열이거나 C ++과 같은 한 쌍을 지원하는 언어 구조 일 수 std::pair있습니다.

곱셈을 1 개의 항목으로 인쇄하거나 첫 번째 요소가 두 번째 요소에 의해 정류 된 항목을 반복하지 마십시오.

승자가 없습니다. 언어 별 코드 골프입니다.


2
30? 같은 작은 테스트 사례를 추가 할 수 있습니까?
caird coinheringaahing

1
@cairdcoinheringaahing factornumber.com 을 사용 하여 더 많은 테스트 사례를 생성 할 수 있습니다 .
Jonathan Frech

1
나는이 "언어 당"경쟁을 최근에 보았다. 점은 무엇인가? 대부분의 Q는 언어별로 1 개 또는 2 개를 초과하지 않으며 A를 하나만 올바르게 선택할 수 있습니다.
페더

5
@ 페더스. 일반적으로 언어 (예 : Java와 Jelly)를 비교할 필요가 없기 때문입니다.
완전히 인간적인

1
@totallyhuman 그래, 알아 내 대답의 대부분은 팩터 또는 스몰 토크에 있습니다. 골프 언어에 반할 가능성이 없습니다. 어휘와 보일러 플레이트
연합에

답변:


6

자바 (OpenJDK 8) , 81 66 65 바이트

  • Olivier Grégoire 덕분에 -15 바이트.
  • -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);}

온라인으로 사용해보십시오!


오래된 것 (참고)

자바 (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 제출 및 첫 번째 람다 사용법. 미래의 자아, 코드를 용서해주십시오.


1
좋은 첫 입장! PPCG에 오신 것을 환영합니다! 여기 에 불필요한 것들을 모두 제거 하여 66 바이트 로 줄였습니다.
Olivier Grégoire



5

파이썬 2 , 51 바이트

f=lambda n,k=2:n/k/k*[f]and[(k,n/k)][n%k:]+f(n,k+1)

온라인으로 사용해보십시오!


51 바이트 (Luis Mendo에게 바이트 감사)

lambda n:[(n/k,k)for k in range(1,n)if(k*k<=n)>n%k]

온라인으로 사용해보십시오!


51 바이트

lambda n:[(n/k,k)for k in range(1,n)if n/k/k>n%k*n]

온라인으로 사용해보십시오!


의 사용을 좋아합니다 [f].
Jonathan Frech

1
당신은 두 번째 버전에서 1 바이트를 저장할 수 있습니다lambda n:[(n/k,k)for k in range(1,n)if(k*k<=n)>n%k]
Luis Mendo

1512518520에 대한 모든 접근 방식에서 MemoryError
sergiol



3

펄 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의 경우 [1, N] 대신 [N]을 제공 하며 나중에이에 의해 컬링됩니다 . 왜 필요한지 잘 모르겠습니다 ...Ċ


1
달리에 대한 선택 사항이 없기 때문에 필요하다 누구의 제품입니다 당신이 실제로 목록의 값을 요구하지 않는 경우 입력이 유일한 해답 길이-2 목록 :.
Fatalize

2

Japt , 9 바이트

â¬Å£[XZo]

온라인으로 테스트하십시오! 끝에 null이있는 배열의 배열을 반환합니다. -R출력을 더 명확하게 표시하기 위해 플래그가 추가되었습니다.


1
나는`-R`이 ... 바이트 카운트 고려되어야한다고 생각합니다 그래서
sergiol

3
@sergiol, 아니요,이 경우 더 나은 가독성을 위해 출력 형식을 지정하기위한 것입니다.
Shaggy

내가 null마지막에 s를 필터링 한 것을 제외하고는 정확히 내가 가진 솔루션 .
Shaggy

2

젤리 , 8 바이트

½ḊpP⁼¥Ðf

숫자를 가져와 숫자 목록 (쌍) 목록을 반환하는 모나드 링크.

온라인으로 사용해보십시오! (에 대한 TIO 시간 초과16777216 예를 들어 680 억 쌍의 목록을 만들고 올바른 제품을 가진 사람들로 필터링하기 때문에 !)

어떻게?

½Ḋ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]]

* , dequeue는 작동하기 전에 숫자 입력의 범위를 암시 적으로 만들고 range 함수는 입력을 암시 적으로 바닥으로 만듭니다 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

자바 스크립트 (ES6), 55 바이트

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

데모

온라인으로 사용해보십시오!


나입니까, 아니면 실패 6합니까?
Neil

@Neil "우리는 고칠 수 있습니다." (보고 주셔서 감사합니다!)
Arnauld

테스트 할 번호를 어떻게 제공 할 수 있습니까?
sergiol


1

파이썬 2 , 59 바이트

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

온라인으로 사용해보십시오!



파이썬은 range(2,N)그것을 평가 하고 목록으로 저장 하려고 시도 하지만 할당 된 메모리로는 충분하지 않습니다. 하나는 교체 시도 할 수 range와 함께 xrange이 최대 런타임 TIO의 1 분 초과하지만, (파이썬 2의 범위 생성기). 메모리와 시간이 충분한 컴퓨터에서이 프로그램은 종료되고 정답을 반환해야합니다.
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.

당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.