/* Configuration */
var QUESTION_ID = 79762; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 43444; // This should be the user ID of the challenge author.
/* App */
var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;
function answersUrl(index) {
return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}
function commentUrl(index, answers) {
return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}
function getAnswers() {
jQuery.ajax({
url: answersUrl(answer_page++),
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function (data) {
answers.push.apply(answers, data.items);
answers_hash = [];
answer_ids = [];
data.items.forEach(function(a) {
a.comments = [];
var id = +a.share_link.match(/\d+/);
answer_ids.push(id);
answers_hash[id] = a;
});
if (!data.has_more) more_answers = false;
comment_page = 1;
getComments();
}
});
}
function getComments() {
jQuery.ajax({
url: commentUrl(comment_page++, answer_ids),
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function (data) {
data.items.forEach(function(c) {
if (c.owner.user_id === OVERRIDE_USER)
answers_hash[c.post_id].comments.push(c);
});
if (data.has_more) getComments();
else if (more_answers) getAnswers();
else process();
}
});
}
getAnswers();
var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;
var OVERRIDE_REG = /^Override\s*header:\s*/i;
function getAuthorName(a) {
return a.owner.display_name;
}
function process() {
var valid = [];
answers.forEach(function(a) {
var body = a.body;
a.comments.forEach(function(c) {
if(OVERRIDE_REG.test(c.body))
body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
});
var match = body.match(SCORE_REG);
if (match)
valid.push({
user: getAuthorName(a),
size: +match[2],
language: match[1],
link: a.share_link,
});
});
valid.sort(function (a, b) {
var aB = a.size,
bB = b.size;
return aB - bB
});
var languages = {};
var place = 1;
var lastSize = null;
var lastPlace = 1;
valid.forEach(function (a) {
if (a.size != lastSize)
lastPlace = place;
lastSize = a.size;
++place;
var answer = jQuery("#answer-template").html();
answer = answer.replace("{{PLACE}}", lastPlace + ".")
.replace("{{NAME}}", a.user)
.replace("{{LANGUAGE}}", a.language)
.replace("{{SIZE}}", a.size)
.replace("{{LINK}}", a.link);
answer = jQuery(answer);
jQuery("#answers").append(answer);
var lang = a.language;
if (/<a/.test(lang)) lang = jQuery(lang).text();
languages[lang] = languages[lang] || {lang: a.language, user: a.user, size: a.size, link: a.link};
});
var langs = [];
for (var lang in languages)
if (languages.hasOwnProperty(lang))
langs.push(languages[lang]);
langs.sort(function (a, b) {
if (a.lang > b.lang) return 1;
if (a.lang < b.lang) return -1;
return 0;
});
for (var i = 0; i < langs.length; ++i)
{
var language = jQuery("#language-template").html();
var lang = langs[i];
language = language.replace("{{LANGUAGE}}", lang.lang)
.replace("{{NAME}}", lang.user)
.replace("{{SIZE}}", lang.size)
.replace("{{LINK}}", lang.link);
language = jQuery(language);
jQuery("#languages").append(language);
}
}
body { text-align: left !important}
#answer-list {
padding: 10px;
width: 290px;
float: left;
}
#language-list {
padding: 10px;
width: 290px;
float: left;
}
table thead {
font-weight: bold;
}
table td {
padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">
<div id="answer-list">
<h2>Leaderboard</h2>
<table class="answer-list">
<thead>
<tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>
</thead>
<tbody id="answers">
</tbody>
</table>
</div>
<div id="language-list">
<h2>Winners by Language</h2>
<table class="language-list">
<thead>
<tr><td>Language</td><td>User</td><td>Score</td></tr>
</thead>
<tbody id="languages">
</tbody>
</table>
</div>
<table style="display: none">
<tbody id="answer-template">
<tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
</tbody>
</table>
<table style="display: none">
<tbody id="language-template">
<tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
</tbody>
</table>
n
être une chaîne d'entrée?n!
tiendrait dans votre type entier! Eh bien, peut-être une autre fois.Réponses:
Python 2, 27 octets
Les zéros de fin sont limités par des facteurs de 5. Le nombre de multiples de ce
5
qui est au plusn
estn/5
(avec division des étages), mais cela ne compte pas les facteurs répétés dans des multiples de25, 125, ...
. Pour les obtenir, divisezn
par 5 et recurse.la source
Gelée , 5 octets
Utilise l’approche contre-productive de trouver la factorielle, puis de la factoriser à nouveau, en vérifiant l’exposant de 5 dans la factorisation première.
Essayez-le en ligne!
la source
Croissant Mornington,
19491909 octets-40 octets grâce à NieDzejkob
la source
Mornington Crescent
contestés serait bien. :)Pyth, 6 octets
Essayez ici.
Alternative 7 octets :
La réduction cumulative du
.u/N5
plancher divisée de manière répétée5
jusqu'à obtenir une répétition, ce qui dans ce cas se produit après avoir atteint 0.Le premier élément est ensuite supprimé (
t
) et le reste est ajouté (s
).la source
En fait, 10 octets
Essayez-le en ligne!
Notez que le dernier cas de test échoue lors de l’exécution sérieuse de CPython car
math.factorial
utilise une extension C (limitée aux entiers 64 bits). Courir sérieusement sur PyPy fonctionne bien, cependant.Explication:
la source
Haskell, 26 octets
Floor divise l’entrée par
5
, puis ajoute le résultat à la fonction appelée. L'expression(+)=<<f
prend une entréex
et des sortiesx+(f x)
.Raccourci de:
Une expression non récursive a donné 28 octets:
la source
i
qu'un compteur1..n
?log_5(n)
question, le reste donne 0.MATL , 9 octets
Essayez-le en ligne!
Cela fonctionne pour de très grands nombres, car cela évite de calculer la factorielle.
Comme d’autres réponses, cela exploite le fait que le nombre de fois
2
indiqué comme diviseur de la factorielle est supérieur ou égal au nombre de fois où il5
apparaît.la source
05AB1E, 5 octets
Serait 4 octets si nous pouvions garantir n> 4
Code:
Explication:
Solution alternative, beaucoup plus rapide, à 6 octets: Inspirée de la réponse MATL de Luis Mendo
Explication:
Edit: solutions supprimées en utilisant ¢ (nombre), car tous les nombres premiers contenant 5 seraient comptés comme 5, par exemple 53.
Edit 2: ajout d'une solution plus efficace pour une entrée plus élevée à titre de comparaison.
la source
5¢
,5Q
ça devrait marcher. Bonne réponse cependant! :)Ó
est lenteÎ!Ó2é
. Le bug a été corrigé hier .Î!Ó7è
8 octets et la solution "6 octets" 10 octetsMatlab
(59) (54)(39)Salut papa !!!! nous vous avons entendu comme maths ....
Ceci est basé sur ma réponse créée dans la révision du code .
plus loin que ce qui est mentionné dans ma réponse dans la révision du code, la formule du nombre de zéros dans factorielle (n) est Sum (n / (5 ^ k)) où k varie entre 1 et log_5 (n)
La seule raison triviale pour laquelle il ne peut pas jouer au golf est que ce
log5
n’est pas disponible dans Matlab en tant que fonction intégrée, c’est pourquoi j’ai remplacé log (5) par 1,6, n’importe pas parce qu’il sera de toute façon recouvert.Essaie
la source
Mathematica, 20 octets
IntegerExponent
compte les zéros. Pour le plaisir, voici une version qui ne calcule pas la factorielle:la source
Array
enregistre un octet sur la deuxième solution.C, 28 octets
Explication
Le nombre de zéros à la fin est égal au nombre de cinq composant la factorielle. De ce nombre
1..n
, un cinquième contribue 5, nous allons donc commencer parn/5
. Parmi ceux-cin/5
, un cinquième est un multiple de 25, alors contribuez-en cinq, et ainsi de suite. Nous nous retrouvons avecf(n) = n/5 + n/25 + n/125 + ...
, ce qui estf(n) = n/5 + f(n/5)
. Nous devons mettre fin à la récursion lorsquen
zéro est atteint; nous profitons également du point de séquence à?:
pour divisern
avant l’addition.En prime, ce code est beaucoup plus rapide que celui qui visite chaque
1..n
(and much, much faster than computing the factorial).Programme de test
Test de sortie
la source
JavaScript ES6, 20 bytes
Same tactic as in xnor's answer, but shorter.
la source
Julia,
343130 bytesThis is an anonymous function that accepts any signed integer type and returns an integer. To call it, assign it to a variable. The larger test cases require passing
n
as a larger type, such as aBigInt
.We compute the factorial of
n
(manually usingprod
is shorter than the built-infactorial
), get an array of itsdigits
in reverse order,find
the indices of the nonzero elements, get the first such index, and subtract 1.Try it online! (includes all but the last test case because the last takes too long)
Saved a byte thanks to Dennis!
la source
C, 36
Same method as @xnor's answer of counting 5s, but just using a simple for loop instead of recursion.
Ideone.
la source
Retina, 33 bytes
Takes input in unary.
Returns output in unary.
(Note the trailing linefeed.)
Try it online!
How it works:
The first stage:
Slightly ungolfed:
What it does:
11111
that can be matched.5
.(?=1)
assures that the number is positive.+`
means repeat until idempotent.If the input is 100 (in unary), then the text is now:
Second stage:
Just removes all semi-colons.
la source
Ruby, 22 bytes
One of the few times where the Ruby
0
being truthy is a problem for byte count.la source
0
truthy?nil
andfalse
are falsey, and nothing else is. There are a lot of cases where helps out in golf, since having0
be truthy means the index and regex index functions in Ruby returnnil
if there is no match instead of-1
, and some where it is a problem, like empty strings still being truthy.Perl 6, 23 bytes
I could get it shorter if
^...
was added to Perl 6{sum $_,*div 5^...0}
.It should be more memory efficient for larger numbers if you added a
lazy
modifier betweensum
and the sequence generator.Explanation:
Test:
( That last line is slightly misleading, as MoarVM has to start, load the Perl 6 compiler and runtime, compile the code, and run it. So it actually takes about a second and a half in total.
That is still significantly faster than it was to check the result of the last test with WolframAlpha.com )
la source
Mathcad, [tbd] bytes
Mathcad is sort of mathematical "whiteboard" that allows 2D entry of expressions, text and plots. It uses mathematical symbols for many operations, such as summation, differentiation and integration. Programming operators are special symbols, usually entered as single keyboard combinations of control and/or shift on a standard key.
What you see above is exactly how the Mathcad worksheet looks as it is typed in and as Mathcad evaluates it. For example, changing n from 2016 to any other value will cause Mathcad to update the result from 502 to whatever the new value is.
http://www.ptc.com/engineering-math-software/mathcad/free-download
Mathcad's byte equivalence scoring method is yet to be determined. Taking a symbol equivalence, the solution takes about 24 "bytes" (the while operator can only be entered using the "ctl-]" key combination (or from a toolbar)). Agawa001's Matlab method takes about 37 bytes when translated into Mathcad (the summation operator is entered by ctl-shft-$).
la source
dc, 12 bytes
This defines a function
f
which consumes its input from top of stack, and leaves its output at top of stack. See my C answer for the mathematical basis. We repeatedly divide by 5, accumulating the values on the stack, then add all the results:Test program
Test output
la source
Jolf, 13 bytes
Defines a recursive function which is called on the input. Try it here!
la source
J,
281716 bytesPretty much the same as the non-recursive technique from xnor's answer.
Here's an older version I have kept here because I personally like it more, clocking in at 28 bytes:
Whilst not needed, I have included
x:
in the test cases for extended precision.The last number doesn't work with this function.
Explanation
This works by calculating
n!
, converting it to a string, and checking each member for equality with'0'
. Forn = 15
, this process would be:Now, we use
;._1
to split the list on its first element (zero), boxing each split result, yielding a box filled with aces (a:
) or runs of1
s, like so:We simple obtain the last member (
{:
), unbox it (>
), and perform a summation over it+/
, yielding the number of zeroes.Here is the more readable version:
la source
>:@i.
can be written1+i.
to save a byte.[:#.~'0'=":@!
for 13 bytes by changing the method of counting the trailing 1s.Python 3, 52 bytes
la source
Pyke, 5 bytes
Try it here!
la source
RETURN, 17 bytes
Try it here.
Recursive operator lambda. Usage:
Explanation
la source
Perl,
2422 + 1 (-p
flag) = 23 bytesUsing:
Full program:
la source
Java, 38 bytes
Full program, with ungolfed method:
la source
J, 7 bytes
Monadic function, taking argument on the right.
If
x
is positive,x q: y
returns the exponents in a prime factorization ofy
, for only the firstx
primes. The3
-rd prime is 5 and{:
takes the tail of a list.Note that you have to input integers with an
x
at the end, or else J will treat them as floats.Try it yourself at tryj.tk, though be warned that this online interpreter will complain if you try anything larger than 1343.
If you want something that doesn't compute n! and hence doesn't require it fit in an integer, use the recursive solution
<.@%&5(+$:@)^:*
. (tryj.tk is still whiny on large inputs.)la source
Ruby,
70615149 bytesVersion 3 with thanks to Kenny Lau and daniero
Edit: Turns out you can save two bytes by mapping
to_i
before youreduce
. Weird :PThis function subtracts the sum of
n
's base 5 digits fromn
and then divides that result by 4. This is related to the sum of the geometric series1+5+25+..+5**n = (5**n+1)/4
.As an example (again, with thanks to Kenny Lau), consider
358
(2413
in base 5) minus its base 5 digits.Divide
348
by4
and you getf(358) = 87
.Version 2 with thanks to Kenny Lau
This function calculates
n!
then subtracts thesize
ofn!
from thesize
of(n!).reverse.to_i.to_s
, which removes all the zeroes, thus, returning thesize
of the zeroes themselves.Version 1
This a variation of the "How many
5
s are there in the prime factorization ofn!
?" trick that uses Ruby's simple base conversion builtins.The golfing is a bit of a pain though, with converting from
Integer
toString
toArray
, grabbing part of theArray
and converting that toString
toInteger
again for thereduce
. Any golfing suggestions are welcome.la source
to_i
before reducing:->n{(n-n.to_s(5).chars.map(&:to_i).reduce(:+))/4}
(saves two bytes)Julia,
2119 bytesUses the recursive formula from xnor's answer.
Try it online!
la source
Dyalog APL, 9 bytes
⎕
prompt for number!
factorialize⍕
stringify'0'=
check equality to character zero⊥⍨
count trailing trues**Literally it is a mixed-base to base-10 conversion, using the boolean list as both number and base:
⊥⍨0 1 0 1 1
is the same as0 1 0 1 1⊥⍨0 1 0 1 1
which is0×(0×1×0×1×1) 1×(1×0×1×1) 0×(0×1×1) 1×(1×1) + 1×(1)
which again is two (the number of trailing 1s).la source