나를 도와 줘


23

입력을 감안할 때 n가장 작은 양의 정수 프로그램이나 기능해야 출력 k되도록 n의 가장 가까운 배수로 반올림은 k보다 크다 n.

예.

입력이 주어지면 20출력 값은 다음 3과 같아야합니다 .

  • 의 가장 가까운 배수로 1IS 20이다, 아니 보다 20.

  • 의 가장 가까운 배수로 2IS 20이다, 아니 보다 20.

  • 가장 가까운 복수의 3IS 21, 이상 20이되도록 출력된다.

테스트 사례

#Input  #Output
2       3
4       5
6       4
8       3
10      4
12      7
14      3
16      6
18      4
20      3
22      4
24      5
26      3
28      5
30      4
32      3
34      4
36      8
38      3
40      6
42      4
44      3
46      4
48      5
50      3
52      6
54      4
56      3
58      4
60      7
62      3
64      5
66      4
68      3
70      4
72      11
74      3
76      6
78      4
80      3
82      4
84      5
86      3
88      5
90      4
92      3
94      4
96      7
98      3
1000    6

홀수 입력의 출력은 2 여야합니다.

규칙

  • n 보다 작은 양의 정수 2^32
  • 반올림은 두 배수가 k에서 동일한 거리에있는 n경우 더 큰 것을 선택합니다 ( "반올림" ). 이런 식으로 모든 홀수 n는의 출력을 산출합니다 2.
  • 이것은 이므로 각 언어에서 가장 짧은 코드 승리합니다.

테스트 케이스의 형식을 수정하여 읽기 쉽고 간결하게 만들었습니다. 이것에 문제가 있거나 새로운 예제 중 하나라도 알려면 알려주세요. :)
DJMcMayhem

@Shaggy Done! 목록에서 500 개의 확률과 450 개의 짝수를 제거했습니다.
fireflame241 '

이 순서에 대한 oeis 링크가 있습니까?
James K

@JamesK 이전에 검색했을 때 찾지 못했습니다. OEIS 계정이있는 사람이 만들 수 있습니까?
fireflame241 '

답변:



9

Japt , 6 바이트

@<rX}a

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

설명:

@    <r X}a
XYZ{U<UrX}a
X              // X = 0; Increments when the condition in between {...} fails
   {     }a    // Return the first integer X where:
    U          //   The input
     <U        //   is less than the input
       rX      //     rounded to the nearest multiple of X

2
r내장입니까? o_o
Outgolfer Erik

@EriktheOutgolfer : Japt에는 반올림 또는 내림을위한 내장 기능도 있습니다 :)
Shaggy

5
내가 알고 D :이 기능이 편리 언젠가는 올 것이다
ETHproductions

@Shaggy 그 견과류입니다! o_o_o
Erik

@Oliver :이 기능 함수에 익숙해 지겠다고 확신했습니다. 이제 내 고유 버전은 7 바이트였습니다.o æ@<rX
Shaggy

7

MATL , 13 바이트

tQ:yy/Yo*<fX<

온라인으로 사용해보십시오! 또는 모든 입력을 확인 1하는1000 .

설명

입력을 고려하십시오 6.

t      % Implicit input. Duplicate
       % STACK: 6, 6
Q:     % Add 1, range
       % STACK: 6, [1 2 3 4 5 6 7]
yy     % Duplicate top two elements
       % STACK: 6, [1 2 3 4 5 6 7], 6, [1 2 3 4 5 6 7]
/      % Divide, element-wise
       % STACK: 6, [1 2 3 4 5 6 7], [6 3 2 1.5 1.2 1 0.8571]
Yo     % Round to closest integer. Halves are rounded up
       % STACK: 6, [1 2 3 4 5 6 7], [6 3 2 2 1 1 1]
*      % Multiply, element-wise
       % STACK: 6, [6 6 6 8 5 6 7]
<      % Less than, element-wise
       % STACK: [0 0 0 1 0 0 1]
f      % Find: indices of nonzeros (1-based)
       % STACK: [4 7]
X<     % Minimum of vector. Implicit display
       % STACK: 4


5

자바 스크립트 (ES6), 28 25 바이트

n=>g=x=>n%x>=x/2?x:g(-~x)
  • Arnauld 덕분에 3 바이트가 절약되었습니다.

그것을 테스트

o.innerText=(f=

n=>g=x=>n%x>=x/2?x:g(-~x)

)(i.value=64)();oninput=_=>o.innerText=f(+i.value)()
<input id=i type=number><pre id=o>

또는 1-1000의 모든 숫자를 테스트하십시오 (1 분 동안 실행).


5

양성자 , 33 바이트

n=>[x for x:2..n+2if n%x>=x/2][0]

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


나는 Proton에 대해 아무것도 모르지만 3 바이트를 절약 할 수있는 것 같습니다 : 온라인으로 시도하십시오!
jferard

어쩌면 우연의 일치는, 그러나 이것은 ... totallyhuman의 솔루션과 완전히 동일합니다 : P
에릭 Outgolfer

@EriktheOutgolfer Hyper는 연산자를 중단 시켰기 때문에 37 바이트와 동시에 (실제로 닌자가 몇 초 정도 그를 네이트했습니다) 게시했습니다.
Mr. Xcoder

어, 나는 IIRC를 닌자했다. : P
완전히 인간적인

@totallyhuman 당신은 41- 바이 터로 나를 닌자했습니다. 나는 37- 바이 터를 먼저 게시했고 몇 초씩 닌자를 썼다.
Mr. Xcoder



3

젤리 , 11 바이트

÷R%1<.¬;1TṂ

양의 정수를 가져오고 리턴하는 모나드 링크.

온라인으로 사용해보십시오! 또는 테스트 스위트를 참조하십시오.

방법?

÷R%1<.¬;1TṂ - Link: number, n       e.g. 10
 R          - range(n)               [ 1,2,3     ,4  ,5,6     ,7     ,8   ,9     ,10]
÷           - n divided by           [10,5,3.33..,2.5,2,1.66..,1.42..,1.25,1.11..,1 ]
  %1        - modulo by 1            [ 0,0,0.33..,0.5,0,0.66..,0.42..,0.25,0.11..,0 ]
    <.      - less than 0.5?         [ 1,1,1     ,0  ,1,0     ,1     ,1   ,1     ,1 ]
      ¬     - not                    [ 0,0,0     ,1  ,0,1     ,0     ,0   ,0     ,0 ]
       ;1   - concatenate a 1        [ 0,0,0     ,1  ,0,1     ,0     ,0   ,0     ,0 , 1]
         T  - truthy indices         [            4    ,6                           ,11]
          Ṃ - minimum                4

참고 :의 연결은 1사건 처리 그냥 n중 하나입니다 1, 2또는 4결과가 될 필요가있을 때 n+1( ‘R÷@%1<.¬TṂ것 또한 일을).




2

Pyth, 5 바이트

fgy%Q

테스트 스위트

반올림 기본 제공은 없으며 첫 번째 양의 정수 T 만 확인하면 입력 mod T의 두 배가 T보다 크거나 같습니다.

설명:

fgy%Q
fgy%QTT    Implicit variable introduction.
f          Find the first positive integer T such that the following is truthy:
   %QT     Input % T
  y        Doubled
 g    T    Is greater than or equal to T

2

x86 머신 코드, 17 바이트

이 코드는 재사용 가능한 함수 형태로 기본 반복 솔루션을 구현합니다.

31 F6                   xor    esi, esi
46                      inc    esi         ; set ESI (our temp register) to 1

                     Loop:
89 C8                   mov    eax, ecx    ; copy 'n' to EAX for division
46                      inc    esi         ; eagerly increment temp
99                      cdq                ; extend EAX into EDX:EAX
F7 F6                   div    esi         ; divide EDX:EAX by ESI
01 D2                   add    edx, edx    ; multiply remainder by 2
39 F2                   cmp    edx, esi    ; compare remainder*2 to temp
7C F4                   jb     Loop        ; keep looping if remainder*2 < temp

96                      xchg   eax, esi    ; put result into EAX (1 byte shorter than MOV)
C3                      ret

이 함수는 fastcall 호출 규칙 을 따르므로 단일 매개 변수 ( n)가 ECX레지스터에 전달됩니다 . 반환 값 ( k)은 보통 EAX레지스터에 반환됩니다 .

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


2

자바 8, 42 바이트

에서 람다 IntegerInteger.

n->{for(int f=1;;)if(n%++f*2>=f)return f;}

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

감사의 말

  • Kevin Cruijssen 덕분에 -1 바이트

4
다음 과 같이 first 를 시작 f=1하고 사용하여 바이트를 절약 할 수 있습니다 .++ffn->{for(int f=1;;)if(n%++f*2>=f)return f;}
Kevin Cruijssen


1

4 번째 (2 번째) , 45 바이트

: f 1 begin 1+ 2dup mod over 1+ 2/ >= until ;

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

코드 설명

: f             \ start a new word definition
  1             \ start a counter at 1
  begin         \ start an indefinite loop
    1+          \ add 1 to counter
    2dup mod    \ duplicate input value and counter, get remainder of input/counter
    over 1+ 2/  \ get counter/2 (add 1 to force rounding up)
    >=          \ check if remainder is greater than counter/2
  until         \ end loop if true, otherwise go back to beginning
;               \ end word definition

1

05AB1E , 9 바이트

∞.ΔIs/Dò‹

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

설명

∞.ΔIs/Dò‹ Full code
∞.Δ       Returns the first number for which the following code returns true
             -> stack is [n]
   Is     Push the input and swap the stack -> stack is [input, n]
     /    Divide both of them -> stack is [input/n]
      Dò  Duplicate and round the second -> stack is [input/n, rounded(input/n)]
        ‹ Check if input/n got larger by rounding -> stack is [bool]
             -> if bool is true, abort and return the current number

1

록 스타 , 681 바이트

Thought takes Patience and Control
While Patience is as high as Control
Let Patience be without Control

Give back Patience

Rock takes Art
Love is neverending
Sex is bottomless
Put Thought taking Art & Love into your head
If your head is Sex
Give back Art
Else
Limits are inspiration
Put Art with Limits without your head into the rubbish
Give back the rubbish


Listen to Chance
Questions are unstoppable
Until Questions is Chance
Build Questions up
Put Thought taking Chance, Questions into your mind
Answers are independence (but)
Put Questions over Answers into the world
Put Rock taking the world into the world
If your mind is as big as the world
Say Questions
Break it down

rockstar online을 사용해 볼 수 있지만 코드를 복사하여 붙여 넣어야합니다. 입력 번호를 묻는 메시지가 나타납니다.

Rockstar는 분명히 골프를 위해 만들어지지 않았기 때문에 가장 낮은 바이트 수를 가지지 않았습니다. 대신 로큰롤 가사를 보려고했습니다.

설명:

이것은 다른 것과 같은 솔루션 (python, java)을 기반으로합니다.

Iterate up from 2:
if n % iterator >= ceil(n/2)
    return iterator

먼저 모듈러스와 실링 함수를 정의해야하는데,시를 위해 Thought and Rock이라고합니다.

아래는 다른 변수 이름을 가진 덜 시적인 버전이며 구문이 명확하지 않은 설명입니다. 괄호는 주석을 나타냅니다.

Modulus takes Number and Divisor
While Number is as high as Divisor
Put Number minus Divisor into Number
    (blank line ending While block)
Give back Number (return Number)
    (blank line ending function declaration)
Ceil takes Decimal
Put Modulus taking Decimal, 1 into Remainder
If Remainder is 0
Give back Decimal (return Decimal)
Else
Put Decimal with 1 minus Remainder into Result
Give back Result (return Result)
    (blank line ending if block)
    (blank line ending function declaration)
Listen to Input (Read from STDIN to Input)
Index is 1
Until Index is Input
Build Index up (Increment by 1)
Put Modulus taking Input, Index into LHS
Put Index over 2 into RHS
Put Ceil taking RHS into RHS
If LHS is as big as RHS
Say Index
Break it down (Break from loop)




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