일련의 숫자의 합이 주어진 값을 초과하는 가장 낮은 숫자를 계산하십시오.


14

다음과 같이 정의 된 숫자의 무한 시퀀스가 ​​있다고 가정합니다.

1: 1 = 1
2: 1 + 2 = 3
3: 1 + 3 = 4
4: 1 + 2 + 4 = 7
5: 1 + 5 = 6
6: 1 + 2 + 3 + 6 = 12
7: 1 + 7 = 8
...

순서는 n1과를 포함한 제수의 합입니다 n.

x입력 으로 양의 정수가 주어지면 n보다 큰 결과를 생성하는 가장 낮은 숫자 를 계산하십시오 x.

테스트 사례

f(100) = 48, ∑ = 124
f(25000) = 7200, ∑ = 25389
f(5000000) = 1164240, ∑ = 5088960

예상 출력

프로그램은 다음과 같이 제수와 제수의 합을 모두 반환해야합니다 n.

$ ./challenge 100
48,124

규칙

이것은 코드 골프이므로 각 언어에서 가장 짧은 바이트 단위의 코드가 이깁니다.


4
그 순서는 ns 제수의 합입니까? 아마도 명시 적으로 말하고 싶을 것입니다.
Martin Ender

3
또한 "예상 출력"으로 판단하면 n 및을 모두 원 f(n)하지만 사양의 어느 곳에서도 그렇게 말하지는 않습니다.
Martin Ender

2
보너스는 특히 모호 할 때 나쁩니다 . 나는 이것을 downvoted으로부터 보호하기 위해 그것을 제거하기로 결정했습니다.
Mr. Xcoder

2
다시 확인해 주 f(1000) = 48시겠습니까? 의 제수 합계 48124
caird

3
답변을 수락하기 전에 적어도 일주일을 기다리는 것이 좋습니다. 그렇지 않으면 새 솔루션을 사용하지 않을 수 있습니다.
Zgarb

답변:


8

Brachylog , 9 바이트

∧;S?hf+S>

이 프로그램은 "output variable" .에서 입력을 받고 "input variable"로 출력합니다 ?. 온라인으로 사용해보십시오!

설명

∧;S?hf+S>
∧;S        There is a pair [N,S]
   ?       which equals the output
    h      such that its first element's
     f     factors'
      +    sum
       S   equals S,
        >  and is greater than the input.

암시 적 변수 N는 순서대로 증가하므로 가장 낮은 값이 출력에 사용됩니다.


10

젤리 , 18 12 11 10 바이트

1Æs>¥#ḢṄÆs

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

Mr. Xcoder 덕분에 -1 바이트 !

작동 원리

1Æs>¥#ḢṄÆs - Main link. Argument: n (integer)
1   ¥#     - Find the first n integers where...
 Æs        -   the divisor sum
   >       -   is greater than the input
       Ṅ   - Print...
      Ḣ    -   the first element
        Æs - then print the divisor sum

1필요한지, 어떻게 ¥행동 하는지 설명해 주 시겠습니까?
dylnan

1
는 @dylnan 1알려줍니다 #1에서 계산을 시작하고는 ¥이전의 두 링크 소요 ( Æs>)과 왼쪽 인자가 반복되는으로, (두 개의 인수 즉)은 양자 관계로 적용, 오른쪽 인수가 입력되고.
caird coinheringaahing.

아, 이제 이해가 되네요. #어떤 경우에는 전에 조금 혼란 스러웠습니다.
dylnan



4

껍질 , 12 11 바이트

§eVḟ>⁰moΣḊN

@Zgarb 덕분에 -1 바이트!

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


영리한! 어떻게 ,작동하지 않습니까? (또는 추론이 너무 오래 걸리나요?)
ბიმო

형식을 유추하지만 무한 목록을 출력합니다. 정수를 두 번째 인수로 사용하는 ḟ의 과부하로 인해 발생할 수 있지만 이는 추측에 불과합니다.
Zgarb


4

Japt , 15 바이트

[@<(V=Xâ x}a V]

시도 해봐


설명

정수의 묵시적 입력 U. []배열 래퍼입니다. 첫 번째 요소의 경우, @ }a정확한 값을 반환 할 때까지 계속 실행되고 매번 증가하는 정수 (0부터 시작)를 전달하고 해당 정수의 최종 값을 출력하는 함수입니다. â현재 정수 ( X) 의 제수를 가져 와서 x합산하고 그 결과는 variable에 할당됩니다 V. 보다 작은 지 <확인합니다 . 그러면 배열의 두 번째 요소는 그냥 입니다.UVV


4

클로저 , 127 바이트

(defn f[n](reduce +(filter #(zero?(rem n %))(range 1(inc n)))))
(defn e[n](loop[i 1 n n](if(>(f i)n){i,(f i)}(recur(inc i)n))))

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

-steadybox 덕분에 -4 바이트!


1
사이트에 오신 것을 환영합니다!
caird coinheringaahing

일부 공백은 몇 바이트를 절약하기 위해 제거 할 수 있습니다. 온라인으로 사용해보십시오!
Steadybox

이 경우 reduce교체 할 수 있습니다 apply또한 기능, e비아 익명의 함수로 표현 될 수있는 #(...)구문, 당신은 코드 골프에서 그 이름을 할 필요가 없습니다. #(=(rem n %)0)보다 짧습니다 #(zero?(rem n %)). 그리고 ,공백 임을 기억하십시오 .이 경우 뒤에 공백이 있으면 제거 할 수 있으므로 (올바르게 구문 분석됩니다.
NikoNyrh

@NikoNyrh 동료 클로저 스트를 만나서 반가워요,이 게시물을 곧 수정하겠습니다
Alonoaky

3

루비 , 58 바이트

람다가 허용되는지 확실하지 않기 때문에 전체 프로그램. /어깨를 으쓱하다

gets
$.+=1until$_.to_i.<v=(1..$.).sum{|n|$.%n<1?n:0}
p$.,v

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

설명

gets     # read line ($_ is used instead of v= because it cuts a space)
$.+=1    # $. is "lines read" variable which starts at 1 because we read 1 line
    until     # repeat as long as the next part is not true
$_.to_i  # input, as numeric
  .<v=   # is <, but invoked as function to lower operator prescedence
  (1..$.)        # Range of 1 to n
  .sum{|n|       # .sum maps values into new ones and adds them together
     $.%n<1?n:0  # Factor -> add to sum, non-factor -> 0
  }
p$.,v    # output n and sum

3
람다는 확실히 허용됩니다.
Giuseppe

3

자바 스크립트 (ES6), 61 58 바이트

f=(n,i=1,s=j=0)=>j++<i?f(n,i,i%j?s:s+j):s>n?[i,s]:f(n,++i)
<input type=number min=0 oninput=o.textContent=f(this.value)><pre id=o>

편집 : @Arnauld 덕분에 3 바이트가 절약되었습니다.


"스크립트 오류"가 나타납니다. 545 이상의 값을 입력 할 때
StudleyJr

Safari를 사용해보십시오. 분명히 테일 콜 최적화를 지원합니다. (또는 찾을 수있는 경우 일부 Chrome 버전에서는 "실험용 JavaScript 기능"을 통해이를 사용할 수 있습니다.)
Neil



2

SOGL V0.12 , 14 바이트

1[:Λ∑:A.>?ao←I

여기 사용해보십시오!

설명:

1               push 1
 [              while ToS != 0
  :Λ              get the divisors
    ∑             sum
     :A           save on variable A without popping
       .>?  ←     if greater than the input
          ao        output the variable A
            ←       and stop the program, implicitly outputting ToS - the counter
             I    increment the counter


2

MATL , 12 바이트

`@Z\sG>~}@6M

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

설명

`      % Do...while
  @    %   Push iteration index (1-based)
  Z\   %   Array of divisors
  s    %   Sum of array
  G    %   Push input
  >~   %   Greater than; logical negate. This is the loop condition
}      % Finally (execute on loop exit)
  @    %   Push latest iteration index
  6M   %   Push latest sum of divisors again
       % End (implicit). Run new iteration if top of the stack is true
       % Display stack (implicit)




2

계수 , 88

USE: math.primes.factors [ 0 0 [ drop 1 + dup divisors sum pick over > ] loop rot drop ]

무차별 검색 그것은, 인용 (람다)의 call그것을 x스택, 잎에nf(n) 스택에.

한마디로 :

: f(n)>x ( x -- n f(n) )
  0 0 [ drop 1 + dup divisors sum pick over > ] loop rot drop ;

2

파이썬 3, 163 바이트

def f(x):
    def d(x):return[i for i in range(1,x+1) if x%i==0]
    return min(i for i in range(x) if sum(d(i)) >x),sum(d(min(i for i in range(x) if sum(d(i)) >x)))

3
PPCG에 오신 것을 환영합니다. 좋은 첫 포스트! 골프 측면에서 공백을 제거하고 람다 함수를 사용하여 모든 것을 한 줄로 접고 반복하지 않으면 바이트를 절약 할 수 있습니다. 우리는 또한 일반적으로 TIO와 같은 온라인 테스트 환경에 링크합니다 ( 105 바이트 , 위에서 설명한 기술 사용)
Jonathan Frech

@JonathanFrech : 훌륭한 의견. 일반 및 noobies과 양해 해 주셔서 감사합니다 noob특히)
에릭 Duminil

2

파이썬 3 , 100 바이트

d=lambda y:sum(i+1for i in range(y)if y%-~i<1)
f=lambda x:min((j,d(j))for j in range(x+1)if x<=d(j))

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

이전의 Python 3 시도에 대한 Jonathan Frech 의 의견 덕분 에 파이썬 구문에 대한 지식을 크게 넓혔습니다. 나는 i + 1을위한-~ i 트릭을 생각한 적이 없다.

그러나 그 대답은 1) 최소가 아니며 2) x = 1 (작동하지 않는 쉬운 오류로 인해 x)에서는 작동하지 않습니다. 케이스!).

빠른 설명 : 두 문자 sum(i+1for i in range(y)if y%-~i<1)와 동일 sum(i for i in range(1,y+1)if y%i<1)하지만 두 문자를 저장합니다. Frech 씨께 다시 한번 감사드립니다.

d=lambda y:sum(i+1for i in range(y)if y%-~i<1) 따라서 y의 제수를 반환합니다.

f=lambda x:min((j,d(j))for j in range(x+1)if x<=d(j)) is where I really did work. Since comparing a tuple works in dictionary order, we can compare j,d(j) as easily as we can compare j, and this lets us not have to find the minimal j, store it in a variable, and /then/ compute the tuple in a separate operation. Also, we have to have the <=, not <, in x<=d(j), because d(1) is 1 so if x is 1 you get nothing. This is also why we need range(x+1) and not range(x).

I'd previously had d return the tuple, but then I have to subscript it in f, so that takes three more characters.


1
Welcome to the site and nice first post. You can get to 98 bytes by removing the f= as anonymous functions are perfectly acceptable here!
caird coinheringaahing

You can't call an anonymous function from another line of code, is the problem -- I have a separate print(f(100)) statement to test that the function works.
Michael Boger

That's not a problem here. It's perfectly acceptable and works to not include the f= in your byte count, and is a good way to golf in Python. Check this for more golfing tips in Python!
caird coinheringaahing

Hm. I can equal, but not better, my submission by appending q=range and replacing range with q in both existing instances. Sadly, this doesn't improve it and since lambda is a keyword I can't use it for that, I'd have to do exec() tricks wasting too many characters.
Michael Boger

@MichaelBoger Well, you can call an anonymous function in Python; lambda expressions do not have to be assigned to a variable.
Jonathan Frech

2

Python 2, 81 bytes

def f(n):
 a=b=0
 while b<n:
	a+=1;i=b=0
	while i<a:i+=1;b+=i*(a%i<1)
 return a,b

Try it online!



Replacing the tabs with two spaces makes this work in python 3 at 83 bytes, although to try it I had to put parentheses in the print statement. You can also replace the return statement with a print statement and not need an auxiliary function to print it; the bytes stay the same.
Michael Boger



0

Clojure, 102 bytes

#(loop[i 1](let[s(apply +(for[j(range 1(inc i)):when(=(mod i j)0)]j))](if(> s %)[i s](recur(inc i)))))

0

PHP, 69 bytes

for(;$argv[1]>=$t;)for($t=$j=++$i;--$j;)$t+=$i%$j?0:$j;echo$i,',',$t;

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