Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Bitwise Algorithms
  • MCQs on Bitwise Algorithms
  • Tutorial on Biwise Algorithms
  • Binary Representation
  • Bitwise Operators
  • Bit Swapping
  • Bit Manipulation
  • Count Set bits
  • Setting a Bit
  • Clear a Bit
  • Toggling a Bit
  • Left & Right Shift
  • Gray Code
  • Checking Power of 2
  • Important Tactics
  • Bit Manipulation for CP
  • Fast Exponentiation
Open In App
Next Article:
Primitive root of a prime number n modulo n
Next article icon

Cyclic Redundancy Check and Modulo-2 Division

Last Updated : 27 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Cyclic Redundancy Check or CRC is a method of detecting accidental changes/errors in the communication channel. CRC uses Generator Polynomial which is available on both sender and receiver side.
An example generator polynomial is of the form like x3 + x + 1. This generator polynomial represents key 1011. Another example is x2 + 1 that represents key 101. 
There are two primary variables in CRC:

  • n: Number of bits in data to be sent from sender side
  • k: Number of bits in the key obtained from generator polynomial.

Encoded Data Generation from Generator Polynomial (Sender Side)

  • The binary data is first augmented by adding k-1 zeros in the end of the data.
  • Then, modulo – 2 binary division is used to divide binary data by the key and remainder of division is stored.
  • At last the the remainder is appended at the end of the data to form the encoded data which is later sent.

Checking Error in Transmission (Receiver Side)

  • After receiving the data, to check if the data is error free, perform the modulo-2 division again.
  • If the remainder is 0, then there are not errors, otherwise, the data is faulty and contain transmission errors.

Modulo 2 Division

The process of modulo-2 binary division is the same as the familiar division process we use for decimal numbers. Just that instead of subtraction, we use XOR here.

  • In each step, a copy of the divisor (or data) is XORed with the k bits of the dividend (or key).
  • The result of the XOR operation (remainder) is (n-1) bits, which is used for the next step after 1 extra bit is pulled down to make it n bits long.
  • When there are no bits left to pull down, we have a result. The (n-1)-bit remainder which is appended at the sender side.

Examples:

Case 1: No error in transmission

Data = 100100, Generator Polynomial (Key) = x3 + x2 + 1 (1101)

Sender Side

gfg

The remainder is 001. Thus the data sent is 100100001.

Receiver Side
Code word received at the receiver side 100100001

rational2

The remainder is 0, hence the data received has no errors.

CRC Implementation – O(n) Time and O(n) Space

Case 2: Error in Transmission

Data = 100100, Generator Polynomial (Key) = x3 + x2 + 1 (1101)

Sender Sidesender

The remainder is 001. Thus the data sent is 100100001.

Receiver Side
Let there be an error and code word received at the receiver side 100000001.
receiver n

As the remainder is not 0, hence there is some error detected in the receiver side.

Implementation of Cyclic Redundancy Check

The idea is to firstly generate the encoded data by appending the remainder of modulo – 2 division of data and key in the given data. Then, repeat the same process for the data received, and if the decoded data contains any ‘1’, then there is some error in transmission, otherwise the correct data is received.

Follow the below given step-by-step process:

  • Start by appending n-1 zeroes to data to form a new string str, where n is the length of key.
  • Compute the remainder by calling mod2div with dividend set to str and divisor set to key. In mod2div, first slice dividend to the length of divisor, then repeatedly perform the following:
    • If the first character of the current slice (tmp) is ‘1’, call findXor with divisor and tmp; otherwise, call findXor with a string of pick zeroes and tmp.
    • Append the next bit of dividend to the result and increment pick.
  • The function findXor calculates the XOR of two strings a and b by traversing from index 1 to the end: if corresponding bits are the same, it appends “0” to result, otherwise “1”.
  • After processing the entire dividend, mod2div returns the final remainder. Append this remainder to data to form the encoded codeword.
  • At the receiver side, extract the first n bits of code and perform mod2div with key to obtain curXor. Then, while cur is not equal to code.size, if curXor’s length is not equal to key’s length, append the next bit from code; otherwise, update curXor by performing mod2div on it.
  • Finally, if curXor’s length equals key’s length, perform a final mod2div. If curXor contains any ‘1’, the data is incorrect; otherwise, the data is correct.

Below is given the implementation:

C++
#include <bits/stdc++.h> using namespace std;  // Returns XOR of 'a' and 'b' string findXor(string a, string b) {     int n = b.length();      // Initialize result     string result = "";      // Traverse all bits, if bits are     // same, then XOR is 0, else 1     for (int i = 1; i < n; i++) {         if (a[i] == b[i])             result += "0";         else             result += "1";     }     return result; }  // Performs Modulo-2 division string mod2div(string dividend, string divisor) {     int n = dividend.length();      // Number of bits to be XORed at a time.     int pick = divisor.length();      // Slicing the dividend to appropriate     // length for particular step     string tmp = dividend.substr(0, pick);      while (pick < n) {         if (tmp[0] == '1')              // Replace the dividend by the result             // of XOR and pull 1 bit down             tmp = findXor(divisor, tmp) + dividend[pick];         else              // If leftmost bit is '0', the step cannot             // use the regular divisor; we need to use an             // all-0s divisor.             tmp = findXor(std::string(pick, '0'), tmp)                   + dividend[pick];          // Increment pick to move further         pick += 1;     }      // For the last n bits, we have to carry it out     // normally as increased value of pick will cause     // Index Out of Bounds.     if (tmp[0] == '1')         tmp = findXor(divisor, tmp);     else         tmp = findXor(std::string(pick, '0'), tmp);      return tmp; }  // Function used at the sender side to encode data string encodeData(string data, string key) {     int n = key.length();      // Appends n-1 zeroes at end of data     string str= data + std::string(n - 1, '0');      // find remainder of mod 2 division     string remainder = mod2div(str, key);      // Append remainder in the original data     string codeword = data + remainder;     return codeword; }  // checking if the message received by receiver  // is correct i.e. the remainder is 0 or not int receiver(string code, string key) {     int n = key.length();      // Perform Modulo-2 division and get the remainder     string curXor = mod2div(code.substr(0, n), key);     int cur = n;      // if code and key are of different length     while (cur != code.size()) {         if (curXor.size() != key.size()) {             curXor.push_back(code[cur++]);         }         else {             curXor = mod2div(curXor, key);         }     }      if (curXor.size() == key.size()) {         curXor = mod2div(curXor, key);     }      // Check if the remainder contains any '1'     if (curXor.find('1') != string::npos) {          // Data is incorrect         return 0;      }     else {          // Data is correct         return 1;      } }  int main() {     string data = "100100";     string key = "1101";     cout << "Sender Side" << endl;     cout << "Data : " << data << endl;     cout << "Key : " << key << endl;     cout << "Encoded Data : ";     string code = encodeData(data, key);     cout << code << endl << endl;      cout << "Receiver Side" << endl;     if(receiver(code, key))         cout << "Data is correct";     else         cout << "Data is incorrect";      return 0; } 
Java
import java.util.*;  public class GfG {      // Returns XOR of 'a' and 'b'     static String findXor(String a, String b) {         int n = b.length();          // Initialize result         String result = "";          // Traverse all bits, if bits are         // same, then XOR is 0, else 1         for (int i = 1; i < n; i++) {             if (a.charAt(i) == b.charAt(i))                 result += "0";             else                 result += "1";         }         return result;     }      // Performs Modulo-2 division     static String mod2div(String dividend, String divisor) {         int n = dividend.length();          // Number of bits to be XORed at a time.         int pick = divisor.length();          // Slicing the dividend to appropriate         // length for particular step         String tmp = dividend.substring(0, pick);          while (pick < n) {             if (tmp.charAt(0) == '1')                  // Replace the dividend by the result                 // of XOR and pull 1 bit down                 tmp = findXor(divisor, tmp) + dividend.charAt(pick);             else                  // If leftmost bit is '0', the step cannot                 // use the regular divisor; we need to use an                 // all-0s divisor.                 tmp = findXor("0".repeat(pick), tmp) + dividend.charAt(pick);              // Increment pick to move further             pick += 1;         }          // For the last n bits, we have to carry it out         // normally as increased value of pick will cause         // Index Out of Bounds.         if (tmp.charAt(0) == '1')             tmp = findXor(divisor, tmp);         else             tmp = findXor("0".repeat(pick), tmp);          return tmp;     }      // Function used at the sender side to encode data     static String encodeData(String data, String key) {         int n = key.length();          // Appends n-1 zeroes at end of data         String str = data + "0".repeat(n - 1);          // find remainder of mod 2 division         String remainder = mod2div(str, key);          // Append remainder in the original data         String codeword = data + remainder;         return codeword;     }      // checking if the message received by receiver      // is correct i.e. the remainder is 0 or not     static int receiver(String code, String key) {         int n = key.length();          // Perform Modulo-2 division and get the remainder         String curXor = mod2div(code.substring(0, n), key);         int cur = n;          // if code and key are of different length         while (cur != code.length()) {             if (curXor.length() != key.length()) {                 curXor = curXor + code.charAt(cur);                 cur++;             }             else {                 curXor = mod2div(curXor, key);             }         }          if (curXor.length() == key.length()) {             curXor = mod2div(curXor, key);         }          // Check if the remainder contains any '1'         if (curXor.indexOf('1') != -1) {              // Data is incorrect             return 0;          }         else {              // Data is correct             return 1;          }     }      public static void main(String[] args) {         String data = "100100";         String key = "1101";         System.out.println("Sender Side");         System.out.println("Data : " + data);         System.out.println("Key : " + key);         System.out.print("Encoded Data : ");         String code = encodeData(data, key);         System.out.println(code + "\n");         System.out.println("Receiver Side");         if(receiver(code, key) == 1)             System.out.println("Data is correct");         else             System.out.println("Data is incorrect");     } } 
Python
# Returns XOR of 'a' and 'b' def findXor(a, b):     n = len(b)      # Initialize result     result = ""      # Traverse all bits, if bits are     # same, then XOR is 0, else 1     for i in range(1, n):         if a[i] == b[i]:             result += "0"         else:             result += "1"     return result  # Performs Modulo-2 division def mod2div(dividend, divisor):     n = len(dividend)      # Number of bits to be XORed at a time.     pick = len(divisor)      # Slicing the dividend to appropriate     # length for particular step     tmp = dividend[:pick]      while pick < n:         if tmp[0] == '1':              # Replace the dividend by the result             # of XOR and pull 1 bit down             tmp = findXor(divisor, tmp) + dividend[pick]         else:              # If leftmost bit is '0', the step cannot             # use the regular divisor; we need to use an             # all-0s divisor.             tmp = findXor("0" * pick, tmp) + dividend[pick]          # Increment pick to move further         pick += 1      # For the last n bits, we have to carry it out     # normally as increased value of pick will cause     # Index Out of Bounds.     if tmp[0] == '1':         tmp = findXor(divisor, tmp)     else:         tmp = findXor("0" * pick, tmp)      return tmp  # Function used at the sender side to encode data def encodeData(data, key):     n = len(key)      # Appends n-1 zeroes at end of data     str_val = data + "0" * (n - 1)      # find remainder of mod 2 division     remainder = mod2div(str_val, key)      # Append remainder in the original data     codeword = data + remainder     return codeword  # checking if the message received by receiver  # is correct i.e. the remainder is 0 or not def receiver(code, key):     n = len(key)      # Perform Modulo-2 division and get the remainder     curXor = mod2div(code[:n], key)     cur = n      # if code and key are of different length     while cur != len(code):         if len(curXor) != len(key):             curXor += code[cur]             cur += 1         else:             curXor = mod2div(curXor, key)      if len(curXor) == len(key):         curXor = mod2div(curXor, key)      # Check if the remainder contains any '1'     if '1' in curXor:          # Data is incorrect         return 0      else:          # Data is correct         return 1   if __name__ == "__main__":     data = "100100"     key = "1101"     print("Sender Side")     print("Data : " + data)     print("Key : " + key)     print("Encoded Data : ", end="")     code = encodeData(data, key)     print(code + "\n")     print("Receiver Side")     if receiver(code, key):         print("Data is correct")     else:         print("Data is incorrect") 
C#
using System; using System.Collections.Generic;  public class GfG {      // Returns XOR of 'a' and 'b'     public static string findXor(string a, string b) {         int n = b.Length;          // Initialize result         string result = "";          // Traverse all bits, if bits are         // same, then XOR is 0, else 1         for (int i = 1; i < n; i++) {             if (a[i] == b[i])                 result += "0";             else                 result += "1";         }         return result;     }      // Performs Modulo-2 division     public static string mod2div(string dividend, string divisor) {         int n = dividend.Length;          // Number of bits to be XORed at a time.         int pick = divisor.Length;          // Slicing the dividend to appropriate         // length for particular step         string tmp = dividend.Substring(0, pick);          while (pick < n) {             if (tmp[0] == '1')                  // Replace the dividend by the result                 // of XOR and pull 1 bit down                 tmp = findXor(divisor, tmp) + dividend[pick];             else                  // If leftmost bit is '0', the step cannot                 // use the regular divisor; we need to use an                 // all-0s divisor.                 tmp = findXor(new string('0', pick), tmp) + dividend[pick];              // Increment pick to move further             pick += 1;         }          // For the last n bits, we have to carry it out         // normally as increased value of pick will cause         // Index Out of Bounds.         if (tmp[0] == '1')             tmp = findXor(divisor, tmp);         else             tmp = findXor(new string('0', pick), tmp);          return tmp;     }      // Function used at the sender side to encode data     public static string encodeData(string data, string key) {         int n = key.Length;          // Appends n-1 zeroes at end of data         string str = data + new string('0', n - 1);          // find remainder of mod 2 division         string remainder = mod2div(str, key);          // Append remainder in the original data         string codeword = data + remainder;         return codeword;     }      // checking if the message received by receiver      // is correct i.e. the remainder is 0 or not     public static int receiver(string code, string key) {         int n = key.Length;          // Perform Modulo-2 division and get the remainder         string curXor = mod2div(code.Substring(0, n), key);         int cur = n;          // if code and key are of different length         while (cur != code.Length) {             if (curXor.Length != key.Length) {                 curXor += code[cur];                 cur++;             }             else {                 curXor = mod2div(curXor, key);             }         }          if (curXor.Length == key.Length) {             curXor = mod2div(curXor, key);         }          // Check if the remainder contains any '1'         if (curXor.IndexOf('1') != -1) {              // Data is incorrect             return 0;          }         else {              // Data is correct             return 1;          }     }      public static void Main(string[] args) {         string data = "100100";         string key = "1101";         Console.WriteLine("Sender Side");         Console.WriteLine("Data : " + data);         Console.WriteLine("Key : " + key);         Console.Write("Encoded Data : ");         string code = encodeData(data, key);         Console.WriteLine(code + "\n");         Console.WriteLine("Receiver Side");         if (receiver(code, key) == 1)             Console.WriteLine("Data is correct");         else             Console.WriteLine("Data is incorrect");     } } 
JavaScript
// Returns XOR of 'a' and 'b' function findXor(a, b) {     let n = b.length;      // Initialize result     let result = "";      // Traverse all bits, if bits are     // same, then XOR is 0, else 1     for (let i = 1; i < n; i++) {         if (a.charAt(i) === b.charAt(i))             result += "0";         else             result += "1";     }     return result; }  // Performs Modulo-2 division function mod2div(dividend, divisor) {     let n = dividend.length;      // Number of bits to be XORed at a time.     let pick = divisor.length;      // Slicing the dividend to appropriate     // length for particular step     let tmp = dividend.substr(0, pick);      while (pick < n) {         if (tmp.charAt(0) === '1')              // Replace the dividend by the result             // of XOR and pull 1 bit down             tmp = findXor(divisor, tmp) + dividend.charAt(pick);         else              // If leftmost bit is '0', the step cannot             // use the regular divisor; we need to use an             // all-0s divisor.             tmp = findXor("0".repeat(pick), tmp) + dividend.charAt(pick);          // Increment pick to move further         pick += 1;     }      // For the last n bits, we have to carry it out     // normally as increased value of pick will cause     // Index Out of Bounds.     if (tmp.charAt(0) === '1')         tmp = findXor(divisor, tmp);     else         tmp = findXor("0".repeat(pick), tmp);      return tmp; }  // Function used at the sender side to encode data function encodeData(data, key) {     let n = key.length;      // Appends n-1 zeroes at end of data     let str = data + "0".repeat(n - 1);      // find remainder of mod 2 division     let remainder = mod2div(str, key);      // Append remainder in the original data     let codeword = data + remainder;     return codeword; }  // checking if the message received by receiver  // is correct i.e. the remainder is 0 or not function receiver(code, key) {     let n = key.length;      // Perform Modulo-2 division and get the remainder     let curXor = mod2div(code.substr(0, n), key);     let cur = n;      // if code and key are of different length     while (cur !== code.length) {         if (curXor.length !== key.length) {             curXor = curXor + code.charAt(cur);             cur++;         }         else {             curXor = mod2div(curXor, key);         }     }      if (curXor.length === key.length) {         curXor = mod2div(curXor, key);     }      // Check if the remainder contains any '1'     if (curXor.indexOf('1') !== -1) {          // Data is incorrect         return 0;      }     else {          // Data is correct         return 1;      } }  function main() {     let data = "100100";     let key = "1101";     console.log("Sender Side");     console.log("Data : " + data);     console.log("Key : " + key);     let code = encodeData(data, key);     console.log("Encoded Data : " + code);     console.log();     console.log("Receiver Side");     if (receiver(code, key))         console.log("Data is correct");     else         console.log("Data is incorrect"); }  main(); 

Output
Sender Side Data : 100100 Key : 1101 Encoded Data : 100100001  Receiver Side Data is correct

CRC Implementation Using Bit Manipulation – O(n) Time and O(n) Space

The idea is to manipulate the given binary strings by converting them to decimal numbers, and process them. After processing the numbers, convert them back to binary strings.

Follow the below given step-by-step approach:

  • Determine n as key.length() and convert key to decimal using toDec(key) to get gen, and convert data to decimal using toDec(data) to get code.
  • Append n-1 zeroes to data by left-shifting code by (n – 1) and store the result in dividend.
  • Compute shft as ceill(log2l(dividend + 1)) – n, which represents the number of least significant bits not involved in the XOR operation.
  • While (dividend >= gen) or (shft >= 0):
    • Calculate rem as (dividend >> shft) XOR gen.
    • Update dividend by combining the unchanged lower shft bits (dividend & ((1 << shft) – 1)) with the new bits (rem << shft) resulting from the XOR operation.
    • Recalculate shft as ceill(log2l(dividend + 1)) – n.
  • After the loop, compute codeword as the bitwise OR of (code << (n – 1)) and dividend.
  • Finally, output the remainder (obtained by converting dividend to binary using toBin(dividend)) and the codeword (obtained by converting codeword to binary using toBin(codeword)).

Below is given the implementation:

C++
// C++ Program to generate CRC codeword #include <bits/stdc++.h> using namespace std; #define int long long int  // function to convert integer to binary string string toBin(int num) {     string bin = "";     while (num) {         if (num & 1)             bin += "1";         else             bin += "0";         num = num >> 1;     }     reverse(bin.begin(), bin.end());      // if the binary string is empty, return "0"     if(bin == "")         bin = "0";     return bin; }  // function to convert binary string to decimal int toDec(string bin) {     int n = bin.size();      // if the binary string is empty, return 0     if (n == 0)         return 0;     int num = 0;     for (int i = 0; i < n; i++) {         if (bin[i] == '1')             num += 1 << (n - i - 1);     }     return num; }  // function to compute CRC and codeword void CRC(string data, string key) {     int n = key.length();      // convert key and data to decimal     int gen = toDec(key);     int code = toDec(data);      // append 0s to dividend     int dividend = code << (n - 1);      // shft specifies the no. of least     // significant bits not being XORed     int shft = (int)ceill(log2l(dividend + 1)) - n;     int rem;      while ((dividend >= gen) || (shft >= 0)) {          // Perform bitwise XOR on the most significant bits          // of the dividend with the key and replace the          // bits in the dividend with the generated remainder         rem = (dividend >> shft) ^ gen;         dividend = (dividend & ((1 << shft) - 1)) | (rem << shft);          // change shft variable         shft = ceill(log2l(dividend + 1)) - n;     }      // find OR of initial dividend with the remainder     int codeword = (code << (n - 1)) | dividend;     cout << "Remainder: " << toBin(dividend) << endl;     cout << "Codeword : " << toBin(codeword); }  signed main() {     string data, key;     data = "100100";     key = "1101";     CRC(data, key);     return 0; } 
Java
import java.util.*;  public class GfG {      // function to convert integer to binary string     static String toBin(long num) {         String bin = "";         while (num != 0) {             if ((num & 1) == 1)                 bin += "1";             else                 bin += "0";             num = num >> 1;         }         StringBuilder sb = new StringBuilder(bin);         bin = sb.reverse().toString();          // if the binary string is empty, return "0"         if (bin.equals(""))             bin = "0";         return bin;     }      // function to convert binary string to decimal     static long toDec(String bin) {         int n = bin.length();          // if the binary string is empty, return 0         if (n == 0)             return 0;         long num = 0;         for (int i = 0; i < n; i++) {             if (bin.charAt(i) == '1')                 num += 1L << (n - i - 1);         }         return num;     }      // function to compute CRC and codeword     static void CRC(String data, String key) {         int n = key.length();          // convert key and data to decimal         long gen = toDec(key);         long code = toDec(data);          // append 0s to dividend         long dividend = code << (n - 1);          // shft specifies the no. of least         // significant bits not being XORed         int shft = (int)          Math.ceil(Math.log(dividend + 1) / Math.log(2)) - n;         long rem;          while ((dividend >= gen) || (shft >= 0)) {              // Perform bitwise XOR on the most significant bits              // of the dividend with the key and replace the              // bits in the dividend with the generated remainder             rem = (dividend >> shft) ^ gen;             dividend = (dividend & ((1L << shft) - 1)) | (rem << shft);              // change shft variable             shft = (int)              Math.ceil(Math.log(dividend + 1) / Math.log(2)) - n;         }          // find OR of initial dividend with the remainder         long codeword = (code << (n - 1)) | dividend;         System.out.println("Remainder: " + toBin(dividend));         System.out.println("Codeword : " + toBin(codeword));     }      public static void main(String[] args) {         String data = "100100";         String key = "1101";         CRC(data, key);     } } 
Python
import math  # function to convert integer to binary string def toBin(num):     bin = ""     while num:         if num & 1:             bin += "1"         else:             bin += "0"         num = num >> 1     bin = bin[::-1]      # if the binary string is empty, return "0"     if bin == "":         bin = "0"     return bin  # function to convert binary string to decimal def toDec(bin):     n = len(bin)      # if the binary string is empty, return 0     if n == 0:         return 0     num = 0     for i in range(n):         if bin[i] == '1':             num += 1 << (n - i - 1)     return num  # function to compute CRC and codeword def CRC(data, key):     n = len(key)      # convert key and data to decimal     gen = toDec(key)     code = toDec(data)      # append 0s to dividend     dividend = code << (n - 1)      # shft specifies the no. of least     # significant bits not being XORed     shft = math.ceil(math.log(dividend + 1, 2)) - n     rem = 0      while (dividend >= gen) or (shft >= 0):          # Perform bitwise XOR on the most significant bits          # of the dividend with the key and replace the          # bits in the dividend with the generated remainder         rem = (dividend >> shft) ^ gen         dividend = (dividend & ((1 << shft) - 1)) | (rem << shft)          # change shft variable         shft = math.ceil(math.log(dividend + 1, 2)) - n      # find OR of initial dividend with the remainder     codeword = (code << (n - 1)) | dividend     print("Remainder: " + toBin(dividend))     print("Codeword : " + toBin(codeword))  if __name__ == "__main__":     data = "100100"     key = "1101"     CRC(data, key) 
C#
using System;  public class GfG {      // function to convert integer to binary string     public static string toBin(long num) {         string bin = "";         while (num != 0) {             if ((num & 1) == 1)                 bin += "1";             else                 bin += "0";             num = num >> 1;         }         char[] arr = bin.ToCharArray();         Array.Reverse(arr);         bin = new string(arr);          // if the binary string is empty, return "0"         if (bin == "")             bin = "0";         return bin;     }      // function to convert binary string to decimal     public static long toDec(string bin) {         int n = bin.Length;          // if the binary string is empty, return 0         if (n == 0)             return 0;         long num = 0;         for (int i = 0; i < n; i++) {             if (bin[i] == '1')                 num += 1L << (n - i - 1);         }         return num;     }      // function to compute CRC and codeword     public static void CRC(string data, string key) {         int n = key.Length;          // convert key and data to decimal         long gen = toDec(key);         long code = toDec(data);          // append 0s to dividend         long dividend = code << (n - 1);          // shft specifies the no. of least         // significant bits not being XORed         int shft = (int)Math.Ceiling(Math.Log(dividend + 1, 2)) - n;         long rem;          while ((dividend >= gen) || (shft >= 0)) {              // Perform bitwise XOR on the most significant bits              // of the dividend with the key and replace the              // bits in the dividend with the generated remainder             rem = (dividend >> shft) ^ gen;             dividend = (dividend & ((1L << shft) - 1)) | (rem << shft);              // change shft variable             shft = (int)Math.Ceiling(Math.Log(dividend + 1, 2)) - n;         }          // find OR of initial dividend with the remainder         long codeword = (code << (n - 1)) | dividend;         Console.WriteLine("Remainder: " + toBin(dividend));         Console.WriteLine("Codeword : " + toBin(codeword));     }      public static void Main(string[] args) {         string data = "100100";         string key = "1101";         CRC(data, key);     } } 
JavaScript
// C++ Program to generate CRC codeword // Translated to JavaScript function toBin(num) {     let bin = "";     while (num) {         if (num & 1)             bin += "1";         else             bin += "0";         num = num >> 1;     }     bin = bin.split("").reverse().join("");      // if the binary string is empty, return "0"     if (bin === "")         bin = "0";     return bin; }  function toDec(bin) {     let n = bin.length;      // if the binary string is empty, return 0     if (n === 0)         return 0;     let num = 0;     for (let i = 0; i < n; i++) {         if (bin.charAt(i) === '1')             num += 1 << (n - i - 1);     }     return num; }  function CRC(data, key) {     let n = key.length;      // convert key and data to decimal     let gen = toDec(key);     let code = toDec(data);      // append 0s to dividend     let dividend = code << (n - 1);      // shft specifies the no. of least     // significant bits not being XORed     let shft = Math.ceil(Math.log2(dividend + 1)) - n;     let rem;      while ((dividend >= gen) || (shft >= 0)) {          // Perform bitwise XOR on the most significant bits          // of the dividend with the key and replace the          // bits in the dividend with the generated remainder         rem = (dividend >> shft) ^ gen;         dividend = (dividend & ((1 << shft) - 1)) | (rem << shft);          // change shft variable         shft = Math.ceil(Math.log2(dividend + 1)) - n;     }      // find OR of initial dividend with the remainder     let codeword = (code << (n - 1)) | dividend;     console.log("Remainder: " + toBin(dividend));     console.log("Codeword : " + toBin(codeword)); }  function main() {     let data, key;     data = "100100";     key = "1101";     CRC(data, key); }  main(); 

Output
Remainder: 1 Codeword : 100100001


Next Article
Primitive root of a prime number n modulo n

J

Jay Patel
Improve
Article Tags :
  • Bit Magic
  • DSA
  • Modular Arithmetic
Practice Tags :
  • Bit Magic
  • Modular Arithmetic

Similar Reads

  • Number Theory for DSA & Competitive Programming
    What is Number Theory?Number theory is a branch of pure mathematics that deals with the properties and relationships of numbers, particularly integers. It explores the fundamental nature of numbers and their mathematical structures. Number theory has been studied for centuries and has deep connectio
    3 min read
  • Number Theory (Interesting Facts and Algorithms)
    Questions based on various concepts of number theory and different types of number are quite frequently asked in programming contests. In this article, we discuss some famous facts and algorithms:Interesting Facts of Number Theory :1. All 4 digit palindromic numbers are divisible by 11.2. If we repe
    5 min read
  • How to prepare for ACM - ICPC?
    ACM ICPC(Association for Computing Machinery - International Collegiate Programming Contest) is a worldwide annual multi-tiered programming contest being organized for over thirteen years. The contest is sponsored by IBM. This article focuses on what all topics that are important for competitive pro
    7 min read
  • Basics of Number Theory

    • Program to Find GCD or HCF of Two Numbers
      Given two numbers a and b, the task is to find the GCD of the two numbers. Note: The GCD (Greatest Common Divisor) or HCF (Highest Common Factor) of two numbers is the largest number that divides both of them. Examples: Input: a = 20, b = 28Output: 4Explanation: The factors of 20 are 1, 2, 4, 5, 10
      15+ min read

    • Program to find LCM of two numbers
      LCM of two numbers is the smallest number which can be divided by both numbers. Input : a = 12, b = 18Output : 3636 is the smallest number divisible by both 12 and 18 Input : a = 5, b = 11Output : 5555 is the smallest number divisible by both 5 and 11 [Naive Approach] Using Conditional Loop This app
      8 min read

    • Factorial of a Number
      Given the number n (n >=0), find its factorial. Factorial of n is defined as 1 x 2 x ... x n. For n = 0, factorial is 1. We are going to discuss iterative and recursive programs in this post. Examples: Input: n = 5Output: 120Explanation: 5! = 5 * 4 * 3 * 2 * 1 = 120 Input: n = 4Output: 24Explanat
      7 min read

    • Print all prime factors of a given number
      Given a number n, the task is to find all prime factors of n. Examples: Input: n = 24Output: 2 2 2 3Explanation: The prime factorization of 24 is 23×3. Input: n = 13195Output: 5 7 13 29Explanation: The prime factorization of 13195 is 5×7×13×29. Approach: Every composite number has at least one prime
      6 min read

    • Binomial Coefficient
      Given an integer values n and k, the task is to find the value of Binomial Coefficient C(n, k). A binomial coefficient C(n, k) can be defined as the coefficient of x^k in the expansion of (1 + x)^n.A binomial coefficient C(n, k) also gives the number of ways, disregarding order, that k objects can b
      15+ min read

    • Program for nth Catalan Number
      Catalan numbers are defined as a mathematical sequence that consists of positive integers, which can be used to find the number of possibilities of various combinations. The nth term in the sequence denoted Cn, is found in the following formula: [Tex]\frac{(2n)!}{((n + 1)! n!)} [/Tex] The first few
      13 min read

    • Euclid's lemma
      We are given two numbers x and y. We know that a number p divides their product. Can we say for sure that p also divides one of them? The answer is no. For example, consider x = 15, y = 6 and p = 9. p divides the product 15*6, but doesn't divide any of them. What if p is prime? Euclid's lemma states
      1 min read

    • Euclidean algorithms (Basic and Extended)
      The Euclidean algorithm is a way to find the greatest common divisor of two positive integers. GCD of two numbers is the largest number that divides both of them. A simple way to find GCD is to factorize both numbers and multiply common prime factors. Examples: input: a = 12, b = 20Output: 4Explanat
      9 min read

    Modular Arithmetic

    • Modular Arithmetic
      Modular arithmetic is a system of arithmetic for numbers where numbers "wrap around" after reaching a certain value, called the modulus. It mainly uses remainders to get the value after wrap around. It is often referred to as "clock arithmetic. As you can see, the time values wrap after reaching 12
      10 min read

    • Modular Addition
      Modular addition is a fundamental concept in number theory and computer science, widely used in cryptography, coding theory, and digital signal processing. It involves performing addition within the confines of a modulus, where numbers wrap around upon reaching a certain value. This article explores
      5 min read

    • Modular Multiplication
      Modular arithmetic, or clock arithmetic, is a system of arithmetic for integers, where numbers "wrap around" upon reaching a certain value This mathematical concept is widely used in various fields such as computer science, cryptography, number theory, and even everyday situations like clock time ca
      6 min read

    • Modular Division
      Modular division is the process of dividing one number by another in modular arithmetic. In modular arithmetic, division is defined differently from regular arithmetic because there is no direct "division" operation. Instead, modular division involves multiplying by the modular multiplicative invers
      10 min read

    • Euler's Totient Function
      Euler's Totient function Φ(n) for an input n is the count of numbers in {1, 2, 3, ..., n-1} that are relatively prime to n, i.e., the numbers whose GCD (Greatest Common Divisor) with n is 1. If n is a positive integer and its prime factorization is; [Tex]n = p_1^{e_1} \cdot p_2^{e_2} \cdot \ldots \c
      15+ min read

    • Euler's Totient function for all numbers smaller than or equal to n
      Euler's Totient function ?(n) for an input n is the count of numbers in {1, 2, 3, ..., n} that are relatively prime to n, i.e., the numbers whose GCD (Greatest Common Divisor) with n is 1. For example, ?(4) = 2, ?(3) = 2 and ?(5) = 4. There are 2 numbers smaller or equal to 4 that are relatively pri
      13 min read

    • Modular Exponentiation (Power in Modular Arithmetic)
      Modular Exponentiation is the process of computing: xy (mod  p). where x, y, and p are integers. It efficiently calculates the remainder when xy is divided by p or (xy) % p, even for very large y. Examples : Input: x = 2, y = 3, p = 5Output: 3Explanation: 2^3 % 5 = 8 % 5 = 3.Input: x = 2, y = 5, p =
      8 min read

    • Program to find remainder without using modulo or % operator
      Given two numbers 'num' and 'divisor', find remainder when 'num' is divided by 'divisor'. The use of modulo or % operator is not allowed.Examples : Input: num = 100, divisor = 7 Output: 2 Input: num = 30, divisor = 9 Output: 3 Method 1 : C/C++ Code // C++ program to find remainder without using // m
      9 min read

    • Modular multiplicative inverse
      Given two integers A and M, find the modular multiplicative inverse of A under modulo M.The modular multiplicative inverse is an integer X such that: A * X ≡ 1 (mod M) Note: The value of X should be in the range {1, 2, ... M-1}, i.e., in the range of integer modulo M. ( Note that X cannot be 0 as A*
      15+ min read

    • Multiplicative order
      In number theory, given an integer A and a positive integer N with gcd( A , N) = 1, the multiplicative order of a modulo N is the smallest positive integer k with A^k( mod N ) = 1. ( 0 < K < N ) Examples : Input : A = 4 , N = 7 Output : 3 explanation : GCD(4, 7) = 1 A^k( mod N ) = 1 ( smallest
      7 min read

    • Compute nCr%p using Lucas Theorem
      Given three numbers n, r and p, compute the value of nCr mod p. Examples: Input: n = 10, r = 2, p = 13 Output: 6 Explanation: 10C2 is 45 and 45 % 13 is 6. Input: n = 1000, r = 900, p = 13 Output: 8 We strongly recommend referring below post as a prerequisite of this.Compute nCr % p | Set 1 (Introduc
      12 min read

    • Compute nCr%p using Fermat Little Theorem
      Given three numbers n, r and p, compute the value of nCr mod p. Here p is a prime number greater than n. Here nCr is Binomial Coefficient.Example: Input: n = 10, r = 2, p = 13 Output: 6 Explanation: 10C2 is 45 and 45 % 13 is 6. Input: n = 6, r = 2, p = 13 Output: 2Recommended PracticenCrTry It! We h
      15+ min read

    • Introduction to Chinese Remainder Theorem
      We are given two arrays num[0..k-1] and rem[0..k-1]. In num[0..k-1], every pair is coprime (gcd for every pair is 1). We need to find minimum positive number x such that: x % num[0] = rem[0], x % num[1] = rem[1], .......................x % num[k-1] = rem[k-1] Basically, we are given k numbers which
      7 min read

    • Implementation of Chinese Remainder theorem (Inverse Modulo based implementation)
      We are given two arrays num[0..k-1] and rem[0..k-1]. In num[0..k-1], every pair is coprime (gcd for every pair is 1). We need to find minimum positive number x such that: x % num[0] = rem[0], x % num[1] = rem[1], ....................... x % num[k-1] = rem[k-1] Example: Input: num[] = {3, 4, 5}, rem[
      11 min read

    • Find Square Root under Modulo p | Set 1 (When p is in form of 4*i + 3)
      Given a number 'n' and a prime 'p', find square root of n under modulo p if it exists. It may be given that p is in the form for 4*i + 3 (OR p % 4 = 3) where i is an integer. Examples of such primes are 7, 11, 19, 23, 31, ... etc,Examples: Input: n = 2, p = 7Output: 3 or 4Explanation: 3 and 4 both a
      14 min read

    • Find Square Root under Modulo p | Set 2 (Shanks Tonelli algorithm)
      Given a number ‘n’ and a prime ‘p’, find square root of n under modulo p if it exists. Examples: Input: n = 2, p = 113 Output: 62 62^2 = 3844 and 3844 % 113 = 2 Input: n = 2, p = 7 Output: 3 or 4 3 and 4 both are square roots of 2 under modulo 7 because (3*3) % 7 = 2 and (4*4) % 7 = 2 Input: n = 2,
      15+ min read

    • Modular Division
      Modular division is the process of dividing one number by another in modular arithmetic. In modular arithmetic, division is defined differently from regular arithmetic because there is no direct "division" operation. Instead, modular division involves multiplying by the modular multiplicative invers
      10 min read

    • Cyclic Redundancy Check and Modulo-2 Division
      Cyclic Redundancy Check or CRC is a method of detecting accidental changes/errors in the communication channel. CRC uses Generator Polynomial which is available on both sender and receiver side. An example generator polynomial is of the form like x3 + x + 1. This generator polynomial represents key
      15+ min read

    • Primitive root of a prime number n modulo n
      Given a prime number n, the task is to find its primitive root under modulo n. The primitive root of a prime number n is an integer r between[1, n-1] such that the values of r^x(mod n) where x is in the range[0, n-2] are different. Return -1 if n is a non-prime number. Examples: Input : 7 Output : S
      15 min read

    • Euler's criterion (Check if square root under modulo p exists)
      Given a number 'n' and a prime p, find if square root of n under modulo p exists or not. A number x is square root of n under modulo p if (x*x)%p = n%p. Examples : Input: n = 2, p = 5 Output: false There doesn't exist a number x such that (x*x)%5 is 2 Input: n = 2, p = 7 Output: true There exists a
      11 min read

    • Using Chinese Remainder Theorem to Combine Modular equations
      Given N modular equations: A ? x1mod(m1) . . A ? xnmod(mn) Find x in the equation A ? xmod(m1*m2*m3..*mn) where mi is prime, or a power of a prime, and i takes values from 1 to n. The input is given as two arrays, the first being an array containing values of each xi, and the second array containing
      12 min read

    • Multiply large integers under large modulo
      Given an integer a, b, m. Find (a * b ) mod m, where a, b may be large and their direct multiplication may cause overflow. However, they are smaller than half of the maximum allowed long long int value. Examples: Input: a = 426, b = 964, m = 235Output: 119Explanation: (426 * 964) % 235 = 410664 % 23
      7 min read

    • Compute n! under modulo p
      Given a large number n and a prime p, how to efficiently compute n! % p?Examples : Input: n = 5, p = 13 Output: 3 5! = 120 and 120 % 13 = 3 Input: n = 6, p = 11 Output: 5 6! = 720 and 720 % 11 = 5 A Naive Solution is to first compute n!, then compute n! % p. This solution works fine when the value o
      15+ min read

    • Wilson's Theorem
      Wilson's Theorem is a fundamental result in number theory that provides a necessary and sufficient condition for determining whether a given number is prime. It states that a natural number p > 1 is a prime number if and only if: (p - 1)! ≡ −1 (mod p) This means that the factorial of p - 1 (the p
      2 min read

    Number Theory

    • Introduction to Primality Test and School Method
      Given a positive integer, check if the number is prime or not. A prime is a natural number greater than 1 that has no positive divisors other than 1 and itself. Examples of the first few prime numbers are {2, 3, 5, ...}Examples : Input: n = 11Output: true Input: n = 15Output: false Input: n = 1Outpu
      10 min read

    • Fermat Method of Primality Test
      Given a number n, check if it is prime or not. We have introduced and discussed the School method for primality testing in Set 1.Introduction to Primality Test and School MethodIn this post, Fermat's method is discussed. This method is a probabilistic method and is based on Fermat's Little Theorem.
      10 min read

    • Primality Test | Set 3 (Miller–Rabin)
      Given a number n, check if it is prime or not. We have introduced and discussed School and Fermat methods for primality testing.Primality Test | Set 1 (Introduction and School Method) Primality Test | Set 2 (Fermat Method)In this post, the Miller-Rabin method is discussed. This method is a probabili
      15+ min read

    • Solovay-Strassen method of Primality Test
      We have already been introduced to primality testing in the previous articles in this series. Introduction to Primality Test and School MethodFermat Method of Primality TestPrimality Test | Set 3 (Miller–Rabin)The Solovay–Strassen test is a probabilistic algorithm used to check if a number is prime
      13 min read

    • Legendre's formula - Largest power of a prime p in n!
      Given an integer n and a prime number p, the task is to find the largest x such that px (p raised to power x) divides n!. Examples: Input: n = 7, p = 3Output: x = 2Explanation: 32 divides 7! and 2 is the largest such power of 3. Input: n = 10, p = 3Output: x = 4Explanation: 34 divides 10! and 4 is t
      6 min read

    • Carmichael Numbers
      A number n is said to be a Carmichael number if it satisfies the following modular arithmetic condition: power(b, n-1) MOD n = 1, for all b ranging from 1 to n such that b and n are relatively prime, i.e, gcd(b, n) = 1 Given a positive integer n, find if it is a Carmichael number. These numbers have
      8 min read

    • Number Theory | Generators of finite cyclic group under addition
      Given a number n, find all generators of cyclic additive group under modulo n. Generator of a set {0, 1, ... n-1} is an element x such that x is smaller than n, and using x (and addition operation), we can generate all elements of the set.Examples: Input : 10 Output : 1 3 7 9 The set to be generated
      5 min read

    • Sum of divisors of factorial of a number
      Given a number n, we need to calculate the sum of divisors of factorial of the number. Examples: Input : 4 Output : 60 Factorial of 4 is 24. Divisors of 24 are 1 2 3 4 6 8 12 24, sum of these is 60. Input : 6 Output : 2418 A Simple Solution is to first compute the factorial of the given number, then
      14 min read

    • GFact | 2x + 1(where x > 0) is prime if and only if x is a power of 2
      A number of the form 2x + 1 (where x > 0) is prime if and only if x is a power of 2, i.e., x = 2n. So overall number becomes 22n + 1. Such numbers are called Fermat Number (Numbers of form 22n + 1). The first few Fermat numbers are 3, 5, 17, 257, 65537, 4294967297, .... An important thing to note
      1 min read

    • Sieve of Eratosthenes
      Given a number n, print all primes smaller than or equal to n. It is also given that n is a small number. Examples: Input: n = 10Output: 2 3 5 7Explanation: The prime numbers up to 10 obtained by Sieve of Eratosthenes are 2 3 5 7 . Input: n = 20Output: 2 3 5 7 11 13 17 19Explanation: The prime numbe
      6 min read

    • Program for Goldbach’s Conjecture (Two Primes with given Sum)
      Goldbach's conjecture is one of the oldest and best-known unsolved problems in the number theory of mathematics. Every even integer greater than 2 can be expressed as the sum of two primes. Examples: Input : n = 44 Output : 3 + 41 (both are primes) Input : n = 56 Output : 3 + 53 (both are primes) Re
      12 min read

    • Pollard's Rho Algorithm for Prime Factorization
      Given a positive integer n, and that it is composite, find a divisor of it.Example: Input: n = 12;Output: 2 [OR 3 OR 4]Input: n = 187;Output: 11 [OR 17]Brute approach: Test all integers less than n until a divisor is found. Improvisation: Test all integers less than ?nA large enough number will stil
      14 min read

    Game Theory

    • Minimax Algorithm in Game Theory | Set 1 (Introduction)
      Minimax is a kind of backtracking algorithm that is used in decision making and game theory to find the optimal move for a player, assuming that your opponent also plays optimally. It is widely used in two player turn-based games such as Tic-Tac-Toe, Backgammon, Mancala, Chess, etc.In Minimax the tw
      9 min read

    • Combinatorial Game Theory | Set 2 (Game of Nim)
      We strongly recommend to refer below article as a prerequisite of this. Combinatorial Game Theory | Set 1 (Introduction) In this post, Game of Nim is discussed. The Game of Nim is described by the following rules- “ Given a number of piles in which each pile contains some numbers of stones/coins. In
      15+ min read

    • Combinatorial Game Theory | Set 4 (Sprague - Grundy Theorem)
      Prerequisites : Grundy Numbers/Numbers and MexWe have already seen in Set 2 (https://cdn.geeksforgeeks.org/combinatorial-game-theory-set-2-game-nim/), that we can find who wins in a game of Nim without actually playing the game.Suppose we change the classic Nim game a bit. This time each player can
      15 min read

    Practice Problems

    • Rabin-Karp Algorithm for Pattern Searching
      Given a text T[0. . .n-1] and a pattern P[0. . .m-1], write a function search(char P[], char T[]) that prints all occurrences of P[] present in T[] using Rabin Karp algorithm. You may assume that n > m. Examples: Input: T[] = "THIS IS A TEST TEXT", P[] = "TEST"Output: Pattern found at index 10 In
      15 min read

    • Measure one litre using two vessels and infinite water supply
      There are two vessels of capacities 'a' and 'b' respectively. We have infinite water supply. Give an efficient algorithm to make exactly 1 litre of water in one of the vessels. You can throw all the water from any vessel any point of time. Assume that 'a' and 'b' are Coprimes.Following are the steps
      15 min read

    • Program to find last digit of n'th Fibonacci Number
      Given a number 'n', write a function that prints the last digit of n'th ('n' can also be a large number) Fibonacci number. Examples : Input : n = 0 Output : 0 Input: n = 2 Output : 1 Input : n = 7 Output : 3 Recommended PracticeThe Nth FibonnaciTry It! Method 1 : (Naive Method) Simple approach is to
      13 min read

    • GCD of two numbers when one of them can be very large
      Given two numbers 'a' and 'b' such that (0 <= a <= 10^12 and b <= b < 10^250). Find the GCD of two given numbers.Examples : Input: a = 978 b = 89798763754892653453379597352537489494736 Output: 6 Input: a = 1221 b = 1234567891011121314151617181920212223242526272829 Output: 3 Solution : In
      9 min read

    • Find Last Digit of a^b for Large Numbers
      You are given two integer numbers, the base a (number of digits d, such that 1 <= d <= 1000) and the index b (0 <= b <= 922*10^15). You have to find the last digit of a^b.Examples: Input : 3 10Output : 9Input : 6 2Output : 6Input : 150 53Output : 0 After taking few examples, we can notic
      9 min read

    • Remainder with 7 for large numbers
      Given a large number as a string, find the remainder of number when divided by 7. Examples : Input : num = 1234 Output : 2 Input : num = 1232 Output : 0 Input : num = 12345 Output : 4Recommended PracticeRemainder with 7Try It! Simple Approach is to convert a string into number and perform the mod op
      8 min read

    • Find (a^b)%m where 'a' is very large
      Given three numbers a, b and m where 1<=b,m<=10^6 and 'a' may be very large and contains upto 10^6 digits. The task is to find (a^b)%m. Examples: Input : a = 3, b = 2, m = 4 Output : 1 Explanation : (3^2)%4 = 9%4 = 1 Input : a = 987584345091051645734583954832576, b = 3, m = 11 Output: 10Recomm
      15+ min read

    • Find sum of modulo K of first N natural number
      Given two integer N ans K, the task is to find sum of modulo K of first N natural numbers i.e 1%K + 2%K + ..... + N%K. Examples : Input : N = 10 and K = 2. Output : 5 Sum = 1%2 + 2%2 + 3%2 + 4%2 + 5%2 + 6%2 + 7%2 + 8%2 + 9%2 + 10%2 = 1 + 0 + 1 + 0 + 1 + 0 + 1 + 0 + 1 + 0 = 5.Recommended PracticeReve
      9 min read

    • Count sub-arrays whose product is divisible by k
      Given an integer K and an array arr[], the task is to count all the sub-arrays whose product is divisible by K.Examples: Input: arr[] = {6, 2, 8}, K = 4 Output: 4 Required sub-arrays are {6, 2}, {6, 2, 8}, {2, 8}and {8}.Input: arr[] = {9, 1, 14}, K = 6 Output: 1 Naive approach: Run nested loops and
      15+ min read

    • Partition a number into two divisible parts
      Given a number (as string) and two integers a and b, divide the string in two non-empty parts such that the first part is divisible by a and the second part is divisible by b. If the string can not be divided into two non-empty parts, output "NO", else print "YES" with the two parts. Examples: Input
      15+ min read

    • Find power of power under mod of a prime
      Given four numbers A, B, C and M, where M is prime number. Our task is to compute A raised to power (B raised to power C) modulo M. Example: Input : A = 2, B = 4, C = 3, M = 23Output : 643 = 64 so,2^64(mod 23) = 6 A Naive Approach is to calculate res = BC and then calculate Ares % M by modular expon
      7 min read

    • Rearrange an array in maximum minimum form in O(1) extra space
      Given a sorted array of positive integers, rearrange the array alternately i.e first element should be the maximum value, second minimum value, third-second max, fourth-second min and so on. Examples: Input: arr[] = {1, 2, 3, 4, 5, 6, 7} Output: arr[] = {7, 1, 6, 2, 5, 3, 4}Explanation: First 7 is t
      9 min read

    • Subset with no pair sum divisible by K
      Given an array of integer numbers, we need to find maximum size of a subset such that sum of each pair of this subset is not divisible by K. Examples : Input : arr[] = [3, 7, 2, 9, 1] K = 3 Output : 3 Maximum size subset whose each pair sum is not divisible by K is [3, 7, 1] because, 3+7 = 10, 3+1 =
      7 min read

    • Number of substrings divisible by 6 in a string of integers
      Given a string consisting of integers 0 to 9. The task is to count the number of substrings which when convert into integer are divisible by 6. Substring does not contain leading zeroes. Examples: Input : s = "606". Output : 5 Substrings "6", "0", "6", "60", "606" are divisible by 6. Input : s = "48
      9 min read

    Miscellaneous Practice Problems

    • How to compute mod of a big number?
      Given a big number 'num' represented as string and an integer x, find value of "num % a" or "num mod a". Output is expected as an integer. Examples : Input: num = "12316767678678", a = 10 Output: num (mod a) ? 8 The idea is to process all digits one by one and use the property that xy (mod a) ? ((x
      4 min read

    • BigInteger Class in Java
      BigInteger class is used for the mathematical operation which involves very big integer calculations that are outside the limit of all available primitive data types. In this way, BigInteger class is very handy to use because of its large method library and it is also used a lot in competitive progr
      6 min read

    • Modulo 10^9+7 (1000000007)
      In most programming competitions, we are required to answer the result in 10^9+7 modulo. The reason behind this is, if problem constraints are large integers, only efficient algorithms can solve them in an allowed limited time.What is modulo operation: The remainder obtained after the division opera
      10 min read

    • How to avoid overflow in modular multiplication?
      Consider below simple method to multiply two numbers. C/C++ Code #include <iostream> using namespace std; #define ll long long // Function to multiply two numbers modulo mod ll multiply(ll a, ll b, ll mod) { // Multiply two numbers and then take modulo to prevent // overflow return ((a % mod)
      6 min read

    • RSA Algorithm in Cryptography
      RSA(Rivest-Shamir-Adleman) Algorithm is an asymmetric or public-key cryptography algorithm which means it works on two different keys: Public Key and Private Key. The Public Key is used for encryption and is known to everyone, while the Private Key is used for decryption and must be kept secret by t
      13 min read

geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences