Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Challenge: fastest program wins

Name: Anonymous 2009-04-14 12:59

Write a program in your language that
1.opens a file as arbitrary precision integer.
2.divides the number by 3.
3.stores the binary result in another file.

Name: Anonymous 2009-04-15 10:44

This is best implemented using long division and not reading the entire file in at once. Thus it will scale nicely.

Here's my C program to do this:

/* div3.c */

#include <errno.h>
#include <stdio.h>

typedef unsigned char byte;

int main(int argc, char *argv[])
{
    FILE *fin;
    FILE *fout;
    byte remainder = 0;
    byte remdiv = 0;
    byte buf[4096];
    size_t bytes_read, nums_cnt, n;
   
    if (argc < 3)
    {
        fprintf(stderr, "usage: div3 infile outfile\n");
        return 1;
    }
   
    if (!(fin = fopen(argv[1], "rb")))
    {
        fprintf(stderr, "can't open input file due to error %u\n", errno);
        return 2;
    }
   
    if (!(fout = fopen(argv[2], "wb")))
    {
        fprintf(stderr, "can't open output file due to error %u\n", errno);
        return 3;
    }

    while(!feof(fin))
    {
        bytes_read = fread(&buf, 1, sizeof(buf), fin);
        if (ferror(fin))
        {
            fprintf(stderr, "error %u while reading file\n", errno);
            return 4;
        }

        for (n=0; n<bytes_read; n++)
        {
            switch(remainder)
            {
            case 0:
                remdiv = 0;
                break;
            case 1:
                remdiv = 85;
                break;
            case 2:
                remdiv = 170;
            }
            remainder += buf[n] % 3;
            buf[n] = buf[n]/3 + remainder/3 + remdiv;
            remainder %= 3;
        }
       
        fwrite(buf, 1, bytes_read, fout);
        if (ferror(fout))
        {
            fprintf(stderr, "error %u while writing file\n", errno);
            return 5;
        }
    }
   
    fclose(fin);
    fclose(fout);
   
    return 0;
}

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List