How to use C++ in efficient mode?

Competitive programming is much more popular among both students and the professional programmers. But it always gives the headache of what is the best programming language for competitive programming? Is it python ? is it C++ ? or anything else. What most of us say is , it doesn’t matter what you are going to use. It does matter how you are going to solve the problem. Do we really have to worry about the programming language we use? It’s kind of a tricky problem. Answer is kind of “YES” and kind of “NO”.

If you are a competitive programmer you already know about the feeling when the solution goes time out. That’s the minute you realize life is not only for an one language . Most of the competitive programmers I know usually prefer PYTHON to reduce these kind of situations. Does PYTHON can reduce this “time out” nightmare forever? Not really. Use a recursion to calculate some Fibonacci numbers in with the power of 105 or higher. You will realize even PYTHON has it’s limits. What about C++? Is it a dead language for competitive programming ? until this moment it is not. There are certain ways which can optimize the code with C++. These tricks helps you to overcome the “time out” disaster in certain ways.

· use the auto keyword to declare data types

auto a = 100; // a will become 'int'
auto b = 1LL; // b will become 'long long'
auto c = 1.0; // c will become 'double'
auto d = "variable"; // d will become 'string'

· Fast Multiplication or Division by 2

n = n << 1;   // Multiply n with 2n = n >> 1;   // Divide n by 2

· using “typedef “keyword

typedef long long ll;
typedef pair w;
typedef vector va;
typedef vector vb;
typedef vector vc;

· Swapping of 2 numbers using XOR:

a ^= b;b ^= a;a ^= b;

· Inbuilt GCD function

cout << __gcd(6, 20) << endl;
answer: 2

· Maximum size of the array

· Calculating the number of digits directly

Number of digits in N =floor(log10(N)) + 1;

· Copy Algorithm

int source[5] = {0, 12, 34, 50, 80};
int target[5];
// copy 5 elements from source to target
copy_n(source, 5, target);

These are some basic tricks which can be used to make the coding with C++ efficient. There are many more tricks which helps to make your code efficient and tidy.stay tuned until next time!

computer engineering undergraduate, business development member at AIESEC in JLC , ENSHIN karate yellow belt holder