Calculer le nombre le plus bas où la somme de la séquence de nombres dépasse une valeur donnée


14

Étant donné que vous avez une séquence infinie de nombres définis comme suit:

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

La séquence est la somme des diviseurs de n, y compris 1 et n.

Étant donné un entier positif xen entrée, calculez le nombre le plus bas nqui produira un résultat supérieur à x.

Cas de test

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

Production attendue

Votre programme doit renvoyer les deux n et la somme de ses diviseurs, comme ceci:

$ ./challenge 100
48,124

Règles

Il s'agit de code-golf, donc le code le plus court en octets, dans chaque langue, gagne.


4
Cette séquence n'est-elle que la somme des ndiviseurs s? Vous voudrez probablement le dire explicitement.
Martin Ender

3
En outre, à en juger par votre "sortie attendue", vous voulez les deux n et f(n) , mais vous ne le dites nulle part dans la spécification.
Martin Ender

2
Les bonus sont mauvais , surtout lorsqu'ils sont vagues. J'ai décidé de le retirer, afin d'éviter que ce vote ne soit revu à la baisse.
M. Xcoder

2
Pourriez-vous revérifier f(1000) = 48? La somme des diviseurs de 48est124
caird coinheringaahing

3
Il est bon d'attendre au moins une semaine avant d'accepter une réponse, sinon vous pourriez décourager de nouvelles solutions.
Zgarb

Réponses:


8

Brachylog , 9 octets

∧;S?hf+S>

Ce programme prend les entrées de la "variable de sortie" .et les sorties vers la "variable d'entrée" ?. Essayez-le en ligne!

Explication

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

La variable implicite Nest énumérée dans l'ordre croissant, donc sa valeur légale la plus basse est utilisée pour la sortie.


10

Gelée , 18 12 11 10 octets

1Æs>¥#ḢṄÆs

Essayez-le en ligne!

-1 octet merci à M. Xcoder !

Comment ça fonctionne

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

Pourriez-vous expliquer pourquoi cela 1est nécessaire et comment les ¥actes?
dylnan

1
@dylnan Le 1dit #de commencer à compter à partir de 1 et ¥prend les deux liens précédents ( Æset >) et les applique comme une dyade (c'est-à-dire avec deux arguments), l'argument de gauche étant l'itération et l'argument de droite étant l'entrée.
caird coinheringaahing

Oh, ça a du sens maintenant. #avait été un peu déroutant pour moi dans certains cas.
dylnan

4

Wolfram Language (Mathematica) , 53 octets

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

Essayez-le en ligne!

Essaie toutes les valeurs entre 2 et x + 1, où x est l'entrée.

(La Selectrenvoie une liste de toutes les valeurs qui fonctionnent, mais la fonction {#,f@#}&prend toutes ces valeurs comme entrées, puis ignore toutes ses entrées sauf la première.)



4

Husk , 12 11 octets

§eVḟ>⁰moΣḊN

-1 octet, merci à @Zgarb!

Essayez-le en ligne!


Intelligent! Bizarre mais comment ,ça ne marche pas (ou l'inférence prend trop de temps?).
ბიმო

Il déduit un type, mais génère une liste infinie. Cela peut être causé par la surcharge de ḟ qui prend un entier comme deuxième argument, mais ce n'est qu'une supposition.
Zgarb


4

Japt , 15 octets

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

Essayez-le


Explication

Saisie implicite d'entier U. []est notre wrapper de tableau. Pour le premier élément, @ }aest une fonction qui s'exécute en continu jusqu'à ce qu'elle retourne une valeur véridique, se passant un entier incrémenté (commençant à 0) à chaque fois et sortant la valeur finale de cet entier. âobtient les diviseurs de l'entier courant ( X), les xadditionne et ce résultat est affecté à la variable V. <vérifie si Uest inférieur à V. Le deuxième élément du tableau est alors juste V.


4

Clojure , 127 octets

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

Essayez-le en ligne!

merci à @steadybox pour -4 octets!


1
Bienvenue sur le site!
caird coinheringaahing

Certains espaces peuvent être supprimés pour économiser quelques octets. Essayez-le en ligne!
Steadybox

Dans ce cas, reducepeut être remplacé par apply, la fonction epeut également être exprimée comme une fonction anonyme via la #(...)syntaxe, vous n'avez pas besoin de la nommer sur Code Golf. #(=(rem n %)0)est plus court que #(zero?(rem n %)). Et rappelez-vous que ,c'est un espace, et peut être supprimé dans ce cas au fur et à mesure (, il sera donc analysé correctement.
NikoNyrh

@NikoNyrh ravi de rencontrer un autre clojuriste, je vais bientôt éditer ce post
Alonoaky

3

Rubis , 58 octets

Programme complet car je ne sais pas si les lambdas sont autorisés. /hausser les épaules

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

Essayez-le en ligne!

Explication

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
Les lambdas sont certainement autorisés.
Giuseppe

3

JavaScript (ES6), 61 58 octets

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>

Edit: sauvé 3 octets grâce à @Arnauld.


J'obtiens "Erreur de script". lors de la saisie d'une valeur supérieure à 545
StudleyJr

Essayez d'utiliser Safari; apparemment, il prend en charge Tail Call Optimization. (Ou si vous pouvez les trouver, certaines versions de Chrome l'activent via les "fonctionnalités JavaScript expérimentales".)
Neil



2

SOGL V0.12 , 14 octets

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

Essayez-le ici!

Explication:

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 octets

`@Z\sG>~}@6M

Essayez-le en ligne!

Explication

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

0

PHP, 69 bytes

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

En utilisant notre site, vous reconnaissez avoir lu et compris notre politique liée aux cookies et notre politique de confidentialité.
Licensed under cc by-sa 3.0 with attribution required.