Saturday, April 28, 2012

Factorial

( http://www.spoj.pl/problems/FCTRL/ )

C99 strict:

#include <stdio.h>
// gcc factorial.c -std=c99 -time -o factorial_c99
int zeta(int n) {
    int ret = 0;
    for(int p = 5; p <= n; p*=5)
        ret += n/p;
    return ret;
}

int main() {
    int t, n;
    scanf("%d", &t);
    while(t--) {
        scanf("%d", &n);
        printf("%d\n", zeta(n));
    }
    return 0;
}

JavaScript (Rhino):

ACHTUNG: this code perfectly runs at http://www.ideone.com/, but not by SPOJ lamers.

importPackage(java.io);
importPackage(java.lang);
 
var reader = new BufferedReader( new InputStreamReader(System['in']) );
var t = reader.readLine();
var num = null;

function zeta(n) {
    var ret = 0;
    for(var p = 5; p <= n; p *= 5)
        ret += parseInt(n/p);
    return ret.toString();
}

while(t--) {
    num = reader.readLine();
    if(!num)
        break;

    System.out.println( zeta(num) );
}

No comments:

Post a Comment