You are on page 1of 2

#include <iostream> #include <stdio.

h> using namespace std; const int BUFFER_SIZE=400000; const int EXTRA=30; // well over the size of an integer void read_to_newline(char *buffer) { int c; while (1) { c = getc_unlocked(stdin); if (c == '\n' || c == EOF) { *buffer = '\0'; return; } *buffer++ = c; } } int main() { char buffer[BUFFER_SIZE+EXTRA]; char *end_buffer; char *startptr, *endptr; //n is number of integers to perform calculation on //k is the divisor //inputnum is the number to be divided by k //total is the total number of inputnums divisible by k int n,k,inputnum,total,nbytes; //initialize total to zero total=0; //read in n and k from stdin read_to_newline(buffer); sscanf(buffer, "%i%i",&n,&k); while (1) { // Read a large block of values // There should be one integer per line, with nothing else. // This might truncate an integer! nbytes = fread(buffer, 1, BUFFER_SIZE, stdin); if (nbytes == 0) { cerr << "Reached end of file too early" << endl; break; } // Make sure I read to the next newline. read_to_newline(buffer+nbytes); startptr = buffer; while (n>0) {

inputnum = 0; // I had used strtol but that was too slow // inputnum = strtol(startptr, &endptr, 10); // Instead, parse the integers myself. endptr = startptr; while (*endptr >= '0') { inputnum = inputnum * 10 + *endptr - '0'; endptr++; } // *endptr might be a '\n' or '\0' // Might occur with the last field if (startptr == endptr) { break; } // skip the newline; go to the // first digit of the next number. if (*endptr == '\n') { endptr++; } // Test if this is a factor if (inputnum % k==0) total += 1; // Advance to the next number startptr = endptr; // Reduce the count by one n--; } // Either we are done, or we need new data if (n==0) { break; } } // output value of total printf("%i\n",total); return 0; }

You might also like