The Wayback Machine - https://web.archive.org/web/20240828110659/https://www.geeksforgeeks.org/c-tricks-competitive-programming-c-11/
Open In App

C++ tricks for competitive programming (for C++ 11)

Last Updated : 10 Jun, 2022
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Companies:
Show Topics
Solve Problem
Easy
49.1%
11.5K

We have discussed some tricks in the below post. In this post, some more tricks are discussed. Writing C/C++ code efficiently in Competitive programming Although, practice is the only way that ensures increased performance in programming contests but having some tricks up your sleeve ensures an upper edge and fast debugging. 

1) Checking if the number is even or odd without using the % operator: Although this trick is not much better than using the % operator but is sometimes efficient (with large numbers). Use & operator: 

CPP




if (num & 1)
   cout << "ODD";
else
   cout << "EVEN";


Example: num = 5 Binary: “101 & 1” will be 001, so true num = 4 Binary: “100 & 1” will be 000, so false. 

2) Fast Multiplication or Division by 2 Multiplying by 2 means shifting all the bits to left and dividing by 2 means shifting to the right. Example : 2 (Binary 10): shifting left 4 (Binary 100) and right 1 (Binary 1) 

CPP




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


3) Swapping of 2 numbers using XOR: This method is fast and doesn’t require the use of 3rd variable. 

CPP




// A quick way to swap a and b
a ^= b;
b ^= a;
a ^= b;


4) Avoiding the use of strlen(): 

CPP




//  Use of strlen() can be avoided by:
for (i=0; s[i]; i++)
{
}
// loop breaks when the character array ends.


5) Use of emplace_back() (Discussed here, here and here) Instead of push_back() in STL emplace_back can be used because it is much faster and instead of allocating memory somewhere else and then appending it directly allocates memory in the container. 

6) Inbuilt GCD function: C++ has an inbuilt GCD function and there is no need to explicitly code it. Syntax: __gcd(x, y); 

7) Using Inline functions: We can create inline functions and use them without having to code them up during the contest. Examples: (a) function for sieve, (b) function for palindrome. 

8) Maximum size of the array: We must be knowing that the maximum size of the array declared inside the main function is of the order of 10^6 but if you declare the array globally then you can declare its size up to 10^7. 

9) Calculating the most significant digit: To calculate the most significant digit of any number log can be directly used to calculate it. We can calculate the number of digits and then divide the number by 10^(number of digits-1)

Suppose the number is N then 
Let int K = log10(N); // number of digits in a number=log10(N)+1
And int X = pow(10, K);
Then int ans=N/X will be the most significant digit

C++




#include <bits/stdc++.h>
using namespace std;
 
int MSD(int n){
      if(n == 0)
        return 0;
      int k = log10(n);
    int x = pow(10,k);
    int ans = n/x;
      return ans;
}
 
int main() {
    int n;
    cin >> n;
    cout << MSD(n) << endl;
    return 0;
}


10) Calculating the number of digits directly: To calculate the number of digits in a number, instead of looping you can efficiently use log :

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

11) Efficient trick to know if a number is a power of 2 using the normal technique of division the complexity comes out to be O(logN), but it can be solved using O(v) where v is the number of digits of the number in binary form. 

CPP




/* Function to check if x is power of 2*/
bool isPowerOfTwo (int x)
{
  /* First x in the below expression is
    for the case when x is 0 */
  return x && (!(x&(x-1)));
}


12) C++11 has inbuilt algorithms for the following:

       // are all of the elements positive?
       all_of(first, first+n, ispositive()); 

      // is there at least one positive element?
      any_of(first, first+n, ispositive());

      // are none of the elements positive?
      none_of(first, first+n, ispositive()); 

Please refer Array algorithms in C++ STL (all_of, any_of, none_of, copy_n and itoa) for details. 

13) Copy Algorithm: used to copy elements from one container to another.

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

Please refer Array algorithms in C++ STL (all_of, any_of, none_of, copy_n and itoa) for details. 

14) The Iota Algorithm The algorithm iota() creates a range of sequentially increasing values, as if by assigning an initial value to *first, then incrementing that value using prefix ++. In the following listing, iota() assigns the consecutive values {10, 11, 12, 13, 14} to the array arr, and {‘a’, ‘b’, ‘c’} to the char array c[]. 

CPP




int a[5] = {0};
char c[3] = {0};
 
// changes a to {10, 11, 12, 13, 14}
iota(a, a+5, 10);
iota(c, c+3, 'a'); // {'a', 'b', 'c'}


Please refer Array algorithms in C++ STL (all_of, any_of, none_of, copy_n and itoa) for details. 

15) Initialization in Binary form: In C++ 11 assignments can also be made in binary form. 

CPP




// C++ code to demonstrate working of
// "binary" numbers
#include<iostream>
using namespace std;
int main()
{
    auto number = 0b011;
    cout << number;
    return 0;
}


Output :

3

16) Use of “and” Though not a very productive one, this tip helps you to just use conditional operator and instead of typing &. 

CPP




// C++ code to demonstrate working of "and"
#include<iostream>
using namespace std;
int main()
{
    int a = 10;
    if (a < 20 and a > 5)
      cout << "Yes";
    return 0;
}


Output :

Yes



Previous Article
Next Article

Similar Reads

Tips and Tricks for Competitive Programmers | Set 2 (Language to be used for Competitive Programming)
This is a question asked quite often as in which language should be preferred to be efficient in competitive programming. It is something one should not worry about as what matters is the logic, not the language. Most of the languages are more or less same, but till now the most preferred language is C++, and here are the reasons. Python Simple and
5 min read
Some useful C++ tricks for beginners in Competitive Programming
Here are some of the basic C++ tricks that every beginner in Competitive Programming should follow for increased speed. However, competitive programming can only be mastered with time and lots of practice. These tricks will just help you to save a little time during the contests which sometimes matters a lot. Using the auto keyword to declare data
3 min read
Mathematics Tricks For Competitive Programming In Python 3
Here are some of the exciting features that Python 3.8 provides for programmers in competitive programming. These new features are related to some math functions and algorithms that are frequently used by competitive programmers. The implementation of these features has the time complexity which is the same in case of a program when implemented fro
3 min read
Logarithm tricks for Competitive Programming
Logarithm: is the inverse function of the exponentiation which means the logarithm value of a given number x is the exponent to another number. [Tex]log_b(x) = y, \to b^{y} = x [/Tex] Below are some tricks using Logarithmic function which can be handy in competitive programming. Checking if a number is a power of two or not:Given an integer N, the
15+ min read
Bit Tricks for Competitive Programming
In competitive programming or in general, some problems seem difficult but can be solved very easily with little concepts of bit magic. We have discussed some tricks below in the previous post.Bitwise Hacks for Competitive Programming One-Liner Hacks of Bit Manipulation:One-Liner CodeFunctionx&amp;1 Evaluates to 1 if the number is odd else evaluate
7 min read
Java tricks for competitive programming (for Java 8)
Although the practice is the only way that ensures increased performance in programming contests but having some tricks up your sleeve ensures an upper edge and fast debugging.1) Checking if the number is even or odd without using the % operator:Although this trick is not much better than using a % operator but is sometimes efficient (with large nu
5 min read
Python Tricks for Competitive Coding
Python is one such programming language that makes everything easier and straight forward. Anyone who has dabbled in python for Competitive Coding gets somewhat addicted to its many features. Here is a list of some of its cool features that I've found most useful in a competitive coding environment. The most common function of the Counter Package.
5 min read
Tips and Tricks for Competitive Programmers | Set 1 (For Beginners)
This article is a collection of various tips that would help beginners of Competitive programming to get an insight of things that should or shouldn’t be done. Competitive programming can only be improved by “PRACTICE, PRACTICE AND PRACTICE”. Try to solve as many questions you can solve on sites like practice.geeksforgeeks.org. This will enhance yo
6 min read
Competitive Programming vs General Programming
Programming enthusiasts face a crossroads - Competitive Programming or General Programming? This article sheds light on the distinctions between Competitive Programming vs General Programming, offering a quick guide for those navigating the coding landscape. Whether you're aiming for speed and precision in competitions or tackling real-world projec
3 min read
Dynamic Programming in Game Theory for Competitive Programming
In the fast-paced world of competitive programming, mastering dynamic programming in game theory is the key to solving complex strategic challenges. This article explores how dynamic programming in game theory can enhance your problem-solving skills and strategic insights, giving you a competitive edge. Whether you're a seasoned coder or a newcomer
15+ min read
Top Programming Languages For Competitive Programming
Building an application, running a server, or even implementing a game needs a programming language as the foundation. There are almost more than 700 programming languages which are the most popular ones and this number will increase day by day. But, you don't need to learn all of them. Having a good command of anyone is enough for you to grow your
13 min read
10 C++ Programming Tricks That You Should Know
C++ Programming Language is a powerful, versatile, and compiled language, which means the source code is converted into machine language before the execution. In order to make your code as efficient and effective as possible, you should be aware of the following tricks and techniques. Hence, it's better to know some C++ tricks and tips to reduce a
10 min read
How to read Competitive Programming Questions?
Competitive Programming is considered as a sport in the field of computer science. The culture of this sport is growing day by day and a lot of people are also considering this as a career choice. So, to help the participants with improving their efficiency in this sport, in this post, we have tried to cover all possible things, needed to keep in m
5 min read
Importance of Testing In Competitive Programming
Many times while solving problems, we face issues like time limit exceeds, wrong solution, runtime error, and memory limit exceeds because after designing algorithm we don't test algorithm efficiency, correctness, time complexity and running the algorithm on a large set of inputs for testing purpose. This is where stress testing comes for rescue. S
3 min read
Writing code faster during Competitive Programming in C++
This article focuses on how to implement your solutions and implement them fast while doing competitive programming. Setup Please refer Setting up a C++ Competitive Programming Environment Snippets Snippet is a programming term for a small region of re-usable source Code. A lot of modern text editors like Sublime provide you a functionality to auto
3 min read
Competitive Programming vs Software Development - Where Should I Invest My Time?
Competitive Programming....what comes to your mind first...? most probably you associate the idea of solving the coding questions on GeeksforGeeks, Codechef, Topcoder, Codeforces, Hackerrank, etc. What about Software Development...? Most probably you imagine a person building an application, a website, mobile apps, or a person handling some backend
11 min read
5 Best Languages for Competitive Programming
Needless to say, Competitive Programming is one of the most crucial and popular aspects of a programmer's journey. Though, all the programmers are strongly recommended to participate in such coding challenges to enhance their coding skills and to get various ravishing prizes, rewards, and other career opportunities. Meanwhile, there's a question th
5 min read
Fast I/O for Competitive Programming in Python
In Competitive Programming, it is important to read input as fast as possible to save valuable time. Input/Output in Python can be sometimes time taking in cases when the input is huge or to output any numbers of lines or a huge number of arrays(lists) line after line. Fast Input Normally, the input is taken from STDIN in the form of String using i
3 min read
How to get started with Competitive Programming in JavaScript
Competitive programming is a popular activity among programmers looking to enhance their problem-solving skills and algorithmic thinking. JavaScript is a wonderful language for competitive programming because of how simple it is to use, how powerful its libraries are, and how quickly it can prototype ideas. JavaScript is a great option for programm
5 min read
Why Java Language is Slower Than CPP for Competitive Programming?
Choosing the appropriate language while starting competitive programming is the most important factor. Generally, we choose that language that has short syntax and executes very fast or which is familiar to us, and we know all the working patterns of that particular whether it is Java or C++. Most of the programmers use C++ for competitive programm
5 min read
Points to focus on while doing Competitive Programming
Competitive Programming is vital for one’s development in the coding field. This article is going to discuss some basics points one should keep in mind while competing. Make a list of functions to perform tasks that are encountered frequently in questions and add them to your code in the form of a template. This saves time during contests and helps
5 min read
How to Use int as long long int for Competitive Programming?
Most of the time, input constraints in Competitive programming questions are bigger than the limits of int. Therefore, there is a need to use long int or even long long int. Here let us take two cases so that if a naive user writes correct logic still input is not getting accepted can get to know where the rectification is required. Case 1: Big int
3 min read
Java Generics to Code Efficiently in Competitive Programming
Templates are the foundation of generic programming, which involve writing code in a way that is independent of any particular type. These powerful tools can be used for writing our code effectively. Some cool tricks that may be used in Competitive Programming are given as follows: Fast Input/Output: This uses the time advantage of BufferedReader a
9 min read
Setting up Java Competitive Programming Environment
An operating system is required to be installed on your system. here we will be discussing the setup in windows. However, you can choose any operating system. Install JDK (Java Development Kit) JDK, is a program that allows you to write Java code from the comfort of your desktop. It contains a variety of tools that are very useful for creating, run
5 min read
Creation and Utilisation of Custom Snippets for Competitive programming in VScode
Coding down the whole algorithm from scratch during the online contest can cost you plenty of time and may lead to a bad rank. There is no point in coding the same algorithm you have coded hundreds of times earlier. Why not utilize your previously coded implementations? You can do that by creating custom code snippets and summoning them just by a k
2 min read
Java Competitive Programming Setup in VS Code with Fast I/O and Snippets
Though C++ is the dominating language in the competitive programming universe, there is a fair share of users who still continue to use Java as it has been there seen in the development arena and at the same time can be used competitive programming being fast as it can be toggled to and from where python being slowest among dynamic is hardly seen i
8 min read
Most Critical Mistakes &amp; Tips in Competitive Programming
The moment a beginner hears this word, an image pops up in one's mind where students are sitting in a room full of Computers and coding some out of the world stuff, We'll to be honest it's nothing too hard to grasp so we will be proposing tips that help a programmer to level up faster. So let's begin with the most underrated points on each topic wh
15+ min read
What are Ad Hoc Problems in Competitive Programming?
The Ad Hoc problems are problems that cannot be classified anywhere else in the categories with well-studied solutions since each problem description and its corresponding solution are unique. These problems don't fall under standard categories, there is no specific or general technique exists to solve them. Many Ad Hoc problems are easy, but this
5 min read
Is Competitive Programming Must For Software Development Roles?
Competitive Programming is a mental sport that involves programmers competing against each other within the given time limit. It makes your problem-solving and coding skills better and efficient - also, it provides you with an edge over other candidates during the tech interviews. It makes you an amazing problem solver which is important in softwar
5 min read
What are Online and Offline query-based questions in Competitive Programming
The query-based questions of competitive programming are mainly of two types: Offline Query.Online Query. Offline Query An offline algorithm allows us to manipulate the data to be queried before any answer is printed. This is usually only possible when the queries do not update the original element set before printing the result. Features: Offline
4 min read
Practice Tags :