Обчисліть найменше число, де сума послідовності чисел перевищує задане значення


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
...

Послідовність - це сума дільників n, включаючи 1 і n.

Задавши ціле додатне ціле число x, обчисліть найменше число, nяке дасть результат, більший за x.

Тестові справи

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

Очікуваний вихід

Ваша програма повинна повернути і обидва, n і суму її дільників, наприклад:

$ ./challenge 100
48,124

Правила

Це код-гольф, тому найкоротший код у байтах, виграючи кожну мову.


4
Це послідовність лише сума nдільників s? Ви, ймовірно, захочете це прямо сказати.
Мартін Ендер

3
Також, судячи з вашого "очікуваного результату", ви хочете і те, n і інше f(n), але ви цього не говорите ніде в специфікації.
Мартін Ендер

2
Бонуси погані , особливо коли вони розпливчасті. Я вирішив її зняти, щоб уберегти це від заборони.
Містер Xcoder

2
Ви можете повторно перевірити f(1000) = 48? Сума дільника 48становить124
caird coinheringaahing

3
Добре почекати хоча б тиждень, перш ніж приймати відповідь, інакше ви можете відмовити від нових рішень.
Згарб

Відповіді:


8

Брахілог , 9 байт

∧;S?hf+S>

Ця програма приймає вхід з "вихідної змінної" .та виводить на "змінну входу" ?. Спробуйте в Інтернеті!

Пояснення

∧;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

Спробуйте в Інтернеті!

-1 байт дякую містеру Xcoder !

Як це працює

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це потрібно і як ¥діє?
ділнан

1
@dylnan 1каже , #щоб почати відлік з 1 і ¥приймає попередні два посилання ( Æsі >) , і застосовує їх в якості діади (тобто з двома аргументами), з лівим аргументом є ітерація, а правий аргумент є вхід.
caird coinheringaahing

О, це має сенс зараз. #раніше в деяких випадках мене трохи заплутали.
ділнан

4

Мова Вольфрама (Mathematica) , 53 байти

{#,f@#}&@@Select[Range[x=#]+1,(f=Tr@*Divisors)@#>x&]&

Спробуйте в Інтернеті!

Перевіряє всі значення між 2 і x + 1, де x - вхід.

( SelectПовертає список усіх значень, що працюють, але функція {#,f@#}&приймає все це як входи, а потім ігнорує всі його входи, окрім першого.)



4

Лушпиння , 12 11 байт

§eVḟ>⁰moΣḊN

-1 байт, дякую @Zgarb!

Спробуйте в Інтернеті!


Розумний! Дивно, але як ,це не працює (або висновок займає занадто багато часу?).
ბიმო

Він робить висновок типу, але видає нескінченний список. Це може бути викликано перевантаженням ḟ, яке приймає ціле число як другий аргумент, але це лише здогадка.
Згарб


4

Japt , 15 байт

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

Спробуй це


Пояснення

Неявне введення цілого числа U. []- наша обгортка масиву. Для першого елемента@ }a - це функція, яка працює безперервно, доки вона не повертає істинне значення, щоразу передаючи собі зростаюче ціле число (починаючи з 0) і виводячи кінцеве значення цього цілого числа. âотримує дільники поточного цілого числа ( X), xпідсумовує їх і цей результат присвоюється змінній V. <перевіряє, якщо Uменше V. Другий елемент у масиві тоді просто V.


4

Clojure , 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може бути виражена як анонімна функція через #(...)синтаксис, вам не потрібно називати її в Code Golf. #(=(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
Лямбди, безумовно, дозволені.
Джузеппе

3

JavaScript (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>

Редагувати: збережено 3 байти завдяки @Arnauld.


Я отримую "Помилка сценарію". при введенні значення понад 545
StudleyJr

Спробуйте використовувати Safari; Мабуть, він підтримує оптимізацію дзвінків Tail. (Або якщо ви можете їх знайти, деякі версії Chrome вмикають це за допомогою "Експериментальних функцій JavaScript".)
Neil



2

SOGL V0.12, 14 bytes

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

Try it Here!

Explanation:

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 bytes

`@Z\sG>~}@6M

Try it online!

Explanation

`      % 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

Factor, 88

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

Brute-force search. It's a quotation (lambda), call it with x on the stack, leaves n and f(n) on the stack.

As a word:

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

2

Python 3, 163 bytes

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
Hello and welcome to PPCG; nice first post! From a golfing aspect, you could save some bytes by removing whitespace, using lambda functions, collapsing everything onto one line and not repeating yourself. We also usually link to an online testing environment, like for example TIO (105 bytes, using the techniques described above.)
Jonathan Frech

@JonathanFrech: Excellent comment. Thanks for your patience with noobies in general and noob in particular ;)
Eric Duminil

2

Python 3, 100 bytes

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))

Try it online!

Thanks to Jonathan Frech's comment on the previous python 3 attempt, I have just greatly expanded my knowledge of python syntax. I'd never have thought of the -~i for i+1 trick, which saves two characters.

However, that answer is 1) not minimal and 2) doesn't work for x=1 (due to an off-by-one error which is easy to make while going for brevity; I suggest everyone else check their answers for this edge case!).

Quick explanation: sum(i+1for i in range(y)if y%-~i<1) is equivalent to sum(i for i in range(1,y+1)if y%i<1) but saves two characters. Thanks again to Mr. Frech.

d=lambda y:sum(i+1for i in range(y)if y%-~i<1) therefore returns the divisors of 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)))))


Використовуючи наш веб-сайт, ви визнаєте, що прочитали та зрозуміли наші Політику щодо файлів cookie та Політику конфіденційності.
Licensed under cc by-sa 3.0 with attribution required.