Ce défi consiste à écrire un programme ou un script qui compte la somme de tous les chiffres compris entre 1 et un nombre donné.
Entrée, un entier positif. La sortie, la somme des chiffres de ce nombre et tous les plus petits.
Exemples:
Input: 5
Integer Sequence: 1, 2, 3, 4, 5
Sum of Digits: 1 + 2 + 3 +4 + 5 = 15
Input: 12
Integer Sequence: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12
Sum of Digits: 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 1 + 0 + 1 + 1 + 1 + 2 = 51
Pour être clair, il s’agit de compter la somme des chiffres et non des entiers. Pour les entrées à un chiffre, ce sera la même chose. Cependant, les intrants supérieurs à 10 auront des réponses différentes. Ce serait une réponse incorrecte :
Input: 12
Output: 78
Un autre exemple, pour montrer la différence:
Input: 10
Integer Sequence: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Sum of Integers (INCORRECT RESPONSE): 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55
Digit Sequence: 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 0
Sum of Digits (CORRECT RESPONSE): 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 1 + 0 = 46
Un cas de test plus grand (réponse correcte):
Input: 1000000
Output: 27000001
Règles et directives:
- Le code soumis doit être un programme complet ou un script, pas seulement une fonction. Si le code nécessite des inclus, des importations, etc., ils doivent être inclus dans le code envoyé.
- Le numéro doit être entré par l'utilisateur - non codé en dur. Les entrées peuvent être reçues sous forme d'argument de ligne de commande, fichier, stdin ou tout autre moyen permettant à votre langue de saisir les entrées de l'utilisateur.
- Le code doit être capable de gérer correctement les entrées au moins jusqu’à
(2^64)-1
. - Le code ne doit générer que la somme.
- Les programmes et scripts soumis doivent être faciles à utiliser et ne pas gaspiller en ressources informatiques (par exemple: ils ne doivent pas déclarer des tableaux incroyablement grands contenant tous les caractères). Il n'y a pas de bonus strict ni de pénalité pour cela, mais soyez de bons programmeurs.
Notation:
Le mécanisme de notation principal est basé sur la longueur du code. Les scores les plus bas sont meilleurs. Les bonus et pénalités suivants s'appliquent également:
- -25 Bonus si votre code peut gérer tous les nombres positifs, par exemple:
1234567891234567891234564789087414984894900000000
- -50 Bonus si votre code peut gérer des expressions simples, par exemple
55*96-12
. Pour pouvoir bénéficier de ce bonus, le code doit gérer les+ - / *
opérateurs (addition, soustraction, division, multiplication) et appliquer l'ordre des opérations. La division est la division entière régulière.- L'exemple donné (
55*96-12
) est évalué à5268
. Votre code devrait renvoyer la même chose pour l'une ou l'autre de ces entrées - la réponse correcte est81393
.
- L'exemple donné (
- -10 Bonus si votre code est éligible au bonus -50 et peut gérer l'
^
opérateur (exposant). - -100 Bonus si votre code se qualifie pour le bonus -50 et n'utilise pas
eval
ou similaire pour gérer les expressions. - Pénalité de +300 si votre code repose sur des ressources Web.
55*96-12
revenir?Réponses:
Perl 6: 108 - (25 + 50 + 100) + 0 = -67 points
Solution golfée (dernière ligne basée sur l'excellente solution de xfix ):
Solution sans jeu:
L'étape d'évaluation fonctionne par itération sur chaque symbole
*
,/
,+
,-
, trouvant quand qui se trouve entre deux nombres entiers, par ce que l' utilisation de la fonction qui représente le symbole.Plus en détail: il prend chaque symbole (par exemple
+
) et la fonction infixe qu’il est censé représenter (par exemple,&[+]
qui est le raccourci pour&infix:<+>
et la même fonction que Perl 6 appelle lors de l’exécution1 + 2
) et effectue une substitution globale (s:g[…] = …
qui ressemble à Perl 5).s/…/…/ge
), qui fait correspondre deux entiers séparés par le symbole ((\d+) $sym (\d+)
) et les substitue au résultat de la fonction infixe correspondante appelée avec ces entiers (infix($0, $1)
).Enfin, cette expression évaluée est alimentée
say [+] (1..$expression)».comb
, ce que xfix explique très bien dans sa solution .Désolé d'être si tard à la fête
EDIT: Suppression du support pour les exposants; de toute façon, c’était exactement 10 caractères et l’associativité n’était pas correcte.
la source
my $g
vous voudrez peut-être utiliser quelque chose de prédéclaré (je pense que cela$!
pourrait fonctionner, mais je n'ai pas testé).my$g=get;for <* / + -> {$g~~s:g[(\d+)$^s(\d+){}]=infix:[$^s] |@()};say [+] (1..$g)».comb
Cela réduirait le score à 88 caractères ou -97 pointsMathematica 30- (10 + 50) = -30
Raccourci de 4 caractères grâce à ybeltukov.
Range@n
renvoie les nombres de 1 àn
.Integerdigits@n
décompose chacun de ces nombres en ses chiffres.Total[n,2]
résume les chiffres. Le 2 doit permettre d’additionner différents niveaux, c’est-à-dire des listes de listes.Essai
Expressions
la source
Tr@Flatten
peut être réduite àTotal[...,2]
:IntegerDigits@Range@#~Total~2&
.C:
150138 - (100+50) = -12Very shamefully stealing @Fors answer from here to do the expression evaluation: https://codegolf.stackexchange.com/a/11423/13877
Sample usage:
Note: the expression implementation assumes no operator precedence and consumes values as it receives them; ex,
1+2*3 = 9
rather than the typical7
.la source
sed,
411283 - 25 = 258I can't be bothered to golf it more right now. :-) Not recommended for use with even remotely big integers, but technically it could deal with arbitrarily large integers (you'll likely run out of RAM pretty quickly though, since I (more-or-less have to) encode the number in unary).
Sample use
(Input lines indented for easier reading.)
la source
python, 55-(50+25+10) = -30
In-efficient yet shorter and also able to handle expressions.
EDIT: Thanks Wolframh and legoStormtroopr for the tricks :D
python, 149-(25+50+10) = 64
My first version
input:
output:
la source
xrange
solution on1234567891234567891234564789087414984894900000000
xrange
:Deval(raw_input())
byinput()
. Thewhile
loop could bewhile t:s+=sum(map(int,
t));t-=1
.input()
instead ofeval(raw_input())
, asinput
alreadyeval
s the expression! This means you can get the -10 binus for the power symbol and the -100 bonus for not usingeval
!!!eval
and similar, so I think the -100 wouldn't countPython - 108 chars minus 85 bonuses, 23 strokes, handles very very very large inputs
Most of these solutions seem to be looping over all ints less than the input and adding up all their digit sums. This works, but I feel it's inelegant, and would question whether they're truly eligible for the 25 point bonus, since I don't think they'd be able to handle the input
1234567891234567891234564789087414984894900000000
within our lifetimes. Indeed, on an input ofn
digits, these solutions takeO(10^n)
time. I chose instead to throw some maths at this problem.The set of all
x
digit numbers is isomorphic to the set{0,1,2,3,4,5,6,7,8,9}^x
. For a fixed(n,sig)
there arex
different values forsig
,10^x-1
points with thesig
th index set ton
, and the sum of all digits0-9
is 45. This is all handled byf
.g
is something we're probably all familiar withmagic
takes all the digits in the input number, and iterates over them from least to most significant. It's easiest to track this with an example input, say1,234,567
.To deal with the range
1,234,567-1,234,560
, we must add up all digits from1
to7
, and add on7
times the sum of the other digits, to deal with all numbers greater than1,234,560
. We now need to deal with the remainder.To deal with the range
1,234,560-1,234,500
, we add on the6
(val
), and drop the upper limit to1,234,559
. In making the remainder of the drop, we'll see every single-digit number 6 times (val*f(sig)
). We'll see all the numbers from0
to5
exactly10
times each ((10**sig)*g(val-1)
). We'll see all the other digits in this number exactly 60 times ((val*10**sig)*sum(digits[sig+1:])
). We have now dealt with all numbers strictly greater than1,234,500
. The same logic will apply inductively across all significances.Golfing this, with thanks to WolframH, reduces this solution to
And the sum of the digit sums of all integers up to
1234567891234567891234564789087414984894900000000
is265889343871444927857379407666265810009829069029376
The largest number I've managed to throw at the golfed version is 10^300, at which point the floats start overflowing and numeric instability starts to cause problems. With a quick square-and-multiply exponentiation function, this problem would vanish.
And LaTeX support would be really useful...
la source
2.65889343871e+50
, which is a floating point approximation of the real solution. Apparently you printedint(t)
instead oft
as in the code you gave. That is wrong; the real solution is265889343871444899381999757086453238874482500000214
. Just avoid using floats, i.e. replace**(x-1)
by the shorter**x/10
.d
(because it's used twice). Eliminating the others (and using some tricks) one arrives atd=map(int,str(input()))\nprint sum(v*(10**s*((v-1)/2+sum(d[:~s]))-~s*9*10**s/2)for s,v in enumerate(d[::-1]))
(108 characters). Runs fine on inputs of any size (likeint("1"*1000)
).10**-1
is0.1
, and from there on everything gets turned into floats.1/10
is0
(integer division), and everything can stayint
s.TI-BASIC, 137 - (50 + 10 + 100) = -23
Input handles numbers up to
1E100
and automatically evaluates. Can handle expressions.Although it is an insanely large array, I'm not wasting computer resources (this is run from a calculator).
la source
eval
shouldn't be taken.Scala 66
la source
C,
7774C,
150124 - 25 = 99Here is an alternative version that should technically be eligible for the 25 bonus for "any" positive integer, but it's impractically slow since the algorithm is linear-time in its input. Regardless, it was fun to write. Manually subtracts a number read in as ASCII characters. This version is 150 characters. (Now with horrible, argument-thrashing, loopful code!)
C,
229224 - (50 + 100) = 74Expression-handling variation. Implements operator precedence according to typical rules:
/ * - +
. Limited to 97 tokens = 48 terms.la source
GolfScript 18 - 50 = -32
Explanation: Suppose input is "12":
Stack is
[0,1,2,3,...,12]
.Stack is
"01234...9101112"
.Stack is
"0 1 2 ... 1 0 1 1 1 2"
.Stack is
[0,1,2,...,9,1,0,1,1,1,2]
.Stack is 51, as desired.
The input here could be any valid GolfScript expression, which can include exponents. For example:
Since
2(5 + 5) - 8 = 12
. I think this should qualify for the bonus, but maybe it was expected to be only if in normal form, not the reverse Polish notation of GolfScript.la source
^
as well??
^
, not?
orpow
and etc.Ruby, 37 - 50 = -13
Double eval, all the way across the sky! As with the other Ruby solutions, I think this should theoretically be able to work with arbitrarily large numbers, but execution time would be... dire.
Older version (49 - 50 score)
Assuming the 10 character bonus actually requires the character for exponentiation to be a caret, the shortest way I could think to add that is:
Which costs more characters than the bonus would give.
la source
p"#{[*1..eval(gets)]}".chars.map(&:to_i).inject :+
&
nearly enough in golf. In fact, you don't need the space betweeninject
and:+
either.Perl 6 (28 - 75 + 0 = -47 bytes)
It can handle all positive numbers (however, big ones will take a long while, because currently Perl 6 implementations are slow, but Perl 6 supports big integers natively). It uses
eval
, in order to implement a simple calculator (five character penalty for fifty characters is worth it). It's slow just because current implementations are slow, but in theory, it should be fast enough (when Perl 6 implementations improve, that is). Also, surprisingly, I win with the Mathematica (for now).»
in this code is actually not needed, but I put it here for performance reasons (otherwise, program would allocate entire string. The reason why it's here is that Perl 6 doesn't have infinite strings, but it does have infinite lists.Anyway, you may ask how this code even works. Well, I'm going to pass it part by part.
get.eval
This gets one line (
get
function), and evaluates it (eval
method).1..get.eval
After that, Perl 6 prepares a range object, from
1
to evaluated value. This is a range, so nothing huge is allocated.».comb
.comb
method splits string onto characters (unless called with an argument). For example,'cat'.comb
returns'c', 'a', 't'
.»
maps the list elements, so.comb
is ran on its every item - not only on the list itself (for example,(4, 9)».sqrt
gives2, 3
). This also doesn't allocate more than needed, because Perl 6 has infinite lists (like Haskell, for example).»
character actually not needed, as.comb
can be used directly on the list, but this involves implicit string coercion (and Perl 6 doesn't have infinite strings, so this would waste memory). For example,1, 2, 3
list after conversion to the string returns1 2 3
. For Perl 6, a space is a perfectly fine number meaning 0, so the code would work, even with such conversion. However, it would abuse computing resources.[+]
This is a reduce operator. Basically, between
[]
, you can put an operator to use, in this case+
. The list after reduce operator is reduced, so[+] 1, 2, 3
is1 + 2 + 3
, which is6
. Perl 6 uses separate operators for numbers and strings, so it won't be considered to be concatenation.say
Finally,
say
outputs the result. After all, you want to see the final result, don't you?la source
[+] 1,2,3,4,5,6,7,8,9,10
is1+2+3+4+5+6+7+8+9+10
, am I right?>
can be chained, so3 > 2 > 1
is true. The same property applies to reduce operators, so[>] 3, 2, 1
is still true, as it means3 > 2 > 1
-[>]
can be used to determine if numbers are in descending order.get.Int
instead ofeval
? Does it need math expressions ?sort
without comparison method argument).Perl 31 - No bonuses
Sample output:
Perl 5 with
-p
, 50 - 28 bytes: -22Try it online!
la source
J, 22
Explanation
Evaluation proceeds from right to left.
la source
+/,10#.inv>:i.
would be shorter. But it still a function and not a complete program as OP asked.R, 64 - (50 + 10) = 4
When this is run, the user is asked for input.
Old version (cannot handle expressions): 46 characters:
la source
u<-function(x) utf8ToInt(x)
and so on.u <- utf8ToInt
withoutfunction
. This can be helpful for code golf if the function is used multiple times.Rcheatcodegolf
package, is it legal to use the predefined functions in that package? :-)Batch - (181 - 50) - 131
Just for a bit of fun.
I'll make it a bit more readable:
Old method uses for loop to get output of powershell command, as opposed to writing to and reading from a file:
Set the input to a variable -
v
- using/a
to accept arithmetic expressions.Unfortunately enabling delayed expansion was necessary.
Use a for loop to count from 1 to the inputted value -
v
.In order to handle numbers greater than 9, I had to use powershell to get the length of the string then use another for loop to split that string up, and add it to the sum -
s
.You could change the name of
powershell.exe
top.exe
under C:\WINDOWS\System32\WindowsPowerShell\v1.0\ then call it with justp "&{'%%a'.length-1}
, saving 9 bytes. But that's not really in the spirit of it.Left that second one running while I took my lunch break.
I can't really test it with numbers that are too much larger than this due to how slow it is. However it should work for fairly large numbers.
2147483647
is the largest number it will take (maximum 32 bit integer) before giving the following error -This of course disqualifies me from the challenge.
la source
v
and use%1
directly. 2. You can subtract 1 within your PowerShell script rather than the lengthy@set /a b=%%b-1
which saves you a bunch. With those changes, I have it down to 211 from the original 240. :-)[decimal]
type allows for values up to (2^96)-1.Dyalog APL, 9 – 160* = -151
Try it online!
⎕
get evaluated inpute.g.
"7+5"
gives12
⍳
indices 1 ... n[1,2,3,4,5,6,7,8,9,10,12]
⍕¨
format each number into string["1","2","3","4","5","6","7","8","9","10","11","12"]
∊
enlist (flatten)"123456789101112"
⍎¨
execute each character (yields list of single digit numbers numbers)[1,2,3,4,5,6,7,8,9,1,0,1,1,1,2]
+/
sum51
* Scoring
-50 bonus as it even accepts expressions as input. The expression must be valid APL, which is acceptable according to OP.
-10 bonus because because it also handles the
^
(*
in APL).-100 bonus because expression input is handled without explicit usage of
eval
(i.e.⍎
in APL).la source
eval
or similar to handle expressions." Since⍎¨
seems to execute each character one by one, it's kinda the same as an eval (except it executes the characters one by one instead of all at the same time likeeval
does).⍎¨
is only used to convert digits to integers, not to handle expressions.⎕
kinda an input+eval builtin then, or is eval always done implicitly when expressions are input?⎕
always takes an expression as input, evaluates it, and returns its result. So to input a string, you'd have to put quotes around it. The fact that a related built-in (⍞
) returns the input as raw text shouldn't matter (especially since the symbols indicate that⎕
is the primary input method, and⍞
is a special variant), as otherwise getting the bonus would require implementing a math evaluator — an entirely different task than the main one. I don't like bonuses, and the -100 one is just silly or had APL in mind, but imho, it does seem an exact fit for the bonus.⎕
is indeed the normal way of getting input and automatically handles expressions, I indeed see it fit into the bonus as well, so +1 from me. Bonuses are silly these days anyway, but nice way of utilizing them to minimize your score.C# (161)
Pretty
la source
Python3+Bash (78 - 185 = -107)
If the result of expression is not integer, it will be truncated first. If the result of the expression is negative, the result is undefined.
Use it like:
1: unless you count invoking Python from Bash as such, but I don't think it is the case. If you think that it actually is, then the adjusted score is -7.
la source
Java, 254
Handles expressions. Give whatever expression you desire in target. Handles until the length long can handle. If you clean up taking off all spaces into one line, and no statement to print, it counts to 254 chars (considering the long long words based Java programming).
PS: This is a complete program, not just logic. Words count given for the program, not just the logic.
la source
Java (JDK8), 272
My first challenge I'm in, suggestions are welcome =)
Indented:
la source
CJam, 9 - 25 = -16
CJam is a few months younger than this challenge, so this is not eligible for the green checkmark. Furthermore, this isn't beating Perl in the first place. ;) I quite liked the approach though, so I wanted to post it anyway.
Test it here.
The idea is to create a range from 0 to N. This range is then converted to a string, which just concatenates the integers back to back. For N = 12, we'd get
Then each character is converted to a integer with
:~
(yielding an array of integers), and then summed up with:+
. CJam can deal with arbitrarily big integers.la source
Python 3 + astor,
10171007 bytes - (25 + 50 + 100) = Score:842834saved 10 bytes by removing
ts
and changingp
edit: I am unable to test the ridiculously long integer (1234567891234567891234564789087414984894900000000) [hangs my computer] but from my knowledge, Python 3 supports arbritrarily long integers.
This implementation
usesabuses AST. I wouldn't consider abusing AST as "eval or similar".Too lazy to write ungolfed, so I'll give you an explanation of the classes:
The last line just executes these classes in the appropriate order on the input, to preserve order of operations, and prevent unwanted behavior.
Example usage ($ or > means user input) and by the way, the actual program takes input only once:
la source
C# (108)
Pretty
la source
int
s; in C, everything defaults toint
... Oh, it's C#.Ruby -> 83-50 = 33
"To test" version:
Tests results
la source
C# (80)
Its my another attempt.
Pretty
la source
n--
and+
needed? I don't think it is in other C-style languages.2^64-1
doesn't fit in 64 bits.4.5
; 2) the average sum of 20 digits is90
(2^64
has 20 digits); so the expected value will be around90 * 2^64 ≈ 1.66*10^21
. So you'd need at least71
bits, at most72
.Ruby 69-50 = 19 (or -4)
This can definitely be golfed together but here is the
firstfifth tryIt also works for all numbers but is very slow for them as it runs slower than O(n), so I wouldn't add the -25. If slowness is fine, then it would be -4 though
Ruby 133-50-25 = 58
This is the faster version, that runs in less-than O(n) time (and uses actual math!), so it can provide results for large integers fast, thereby I added the -25:
la source
Haskell, 74-25=49
main=getLine>>=print.sum.map(\c->read[c]).concatMap show.(\x->[0..x]).read
la source
interact
and the fact that>>=
for lists is the same asflip concatMap
, you can golf this down to 63 chars like this:main=interact$show.sum.map(\c->read[c]). \x->[0..read x]>>=show
\c->read[c]
isread.(:[])
ECMAScript 6, 86 - 50 = 36
la source
for(i=eval(prompt(s=""));i;s+=i--)alert(s.replace(/\d/g,c=>Array(-~c).join()).length)
..join()
):for(i=eval(prompt(s=""));i;s+=i--)alert(s.replace(/\d/g,c=>Array(-~c)).length)
. 78 - 50 = 28!R (72 points)
Output:
la source