I am taking part in a small programming competition online. Basically what I do is solve a task, write an algorithm and send my code to be automatically evaluated by the competition holder's server.
The server accepts a wide variety of programming languages. All the tasks basically require the program to take input from the terminal and output a correct to the terminal as well. So on the competition holder's website I noticed that one of the languages they support is C++ and they use g++ to compile it. Well, since I'm not that fluent in C++ as opposed to C I thought I would return my answers in C.
This worked great for the first task. However in the second task I constantly hit the limit set for the execution time of the program (2 seconds)
This is my C code:
#include <inttypes.h>
#include <stdio.h>
#include <stdint.h>
#include <math.h>
#include <stdlib.h>
uint8_t get_bit(uint64_t k) {
...
}
int main(int argc, char *argv[]) {
uint64_t n;
uint64_t k;
scanf("%u", &n);
uint64_t i;
for (i = 0; i < n; i++) {
scanf("%u", &k);
printf("%d\n", get_bit(k));
}
return 0;
}
So my algorithm is defined in get_bit
.
The server runs 3 different tests on my program, with different values, mostly increasing to make the program run longer.
However, this code in C failed the tests due to taking more than 2 seconds to run. Trying different solutions for hours with no avail, I finally tried to submit my code as C++ with a little different printing methods.
Here is my C++ main (the rest of the program stayed mostly the same):
int main(int argc, char *argv[]) {
uint64_t n;
uint64_t k;
cin >> n;
uint64_t i;
for (i = 0; i < n; i++) {
cin >> k;
cout.operator<<(get_bit(k)) << endl;
}
return 0;
}
And when I submitted this code, all the tests ran perfectly in just a few hundred milliseconds each. Note that I did not alter my algorithm in get_bit
but only the printing.
Why is printing in C++ so much faster than in C? (in my case up to 10x faster) If it's possible, how can I achieve these speeds in C as well? As you might probably notice, I am not fluent in C++ and the previous code is mainly copy paste. For this reason I would much rather prefer to program in C.
Thank you in advance.
It is probably because your code is may be (see comments) incorrect. You cant use %u
with scanf
and 64-bit integer.
Check the third table here http://www.cplusplus.com/reference/cstdio/scanf/ . You should use sth like %llu
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With