text
stringlengths
25
2.53k
code
stringlengths
46
4.32k
Pentacontagon number | C program for above approach ; Finding the nth pentacontagon Number ; Driver program to test above function
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE int pentacontagonNum ( int n ) { return ( 48 * n * n - 46 * n ) / 2 ; } int main ( ) { int n = 3 ; printf ( "3rd ▁ pentacontagon ▁ Number ▁ is ▁ = ▁ % d " , pentacontagonNum ( n ) ) ; return 0 ; }
Array value by repeatedly replacing max 2 elements with their absolute difference | C ++ program to find the array value by repeatedly replacing max 2 elements with their absolute difference ; function that return last value of array ; Build a binary max_heap . ; For max 2 elements ; Iterate until queue is not empty ; if only 1 element is left ; return the last remaining value ; check that difference is non zero ; finally return 0 ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int lastElement ( vector < int > & arr ) { priority_queue < int > pq ; for ( int i = 0 ; i < arr . size ( ) ; i ++ ) { pq . push ( arr [ i ] ) ; } int m1 , m2 ; while ( ! pq . empty ( ) ) { if ( pq . size ( ) == 1 ) return pq . top ( ) ; m1 = pq . top ( ) ; pq . pop ( ) ; m2 = pq . top ( ) ; pq . pop ( ) ; if ( m1 != m2 ) pq . push ( m1 - m2 ) ; } return 0 ; } int main ( ) { vector < int > arr = { 2 , 7 , 4 , 1 , 8 , 1 , 1 } ; cout << lastElement ( arr ) << endl ; return 0 ; }
Logarithm tricks for Competitive Programming | C implementation count the number of digits in a number ; Function to count the number of digits in a number ; Driver Code
#include <stdio.h> NEW_LINE #include <math.h> NEW_LINE int countDigit ( long long n ) { return ( floor ( log10 ( n ) + 1 ) ) ; } int main ( ) { double N = 80 ; printf ( " % d " , countDigit ( N ) ) ; return 0 ; }
Program to find the sum of the series 1 + x + x ^ 2 + x ^ 3 + . . + x ^ n | C implementation to find the sum of series 1 + x ^ 2 + x ^ 3 + ... . + x ^ n ; Function to print the sum of the series ; First Term of series ; Loop to find the N terms of the series ; Driver Code
#include <math.h> NEW_LINE #include <stdio.h> NEW_LINE double sum ( int x , int n ) { double i , total = 1.0 , multi = x ; printf ( "1 ▁ " ) ; for ( i = 1 ; i < n ; i ++ ) { total = total + multi ; printf ( " % .1f ▁ " , multi ) ; multi = multi * x ; } printf ( " STRNEWLINE " ) ; return total ; } int main ( ) { int x = 2 ; int n = 5 ; printf ( " % .2f " , sum ( x , n ) ) ; return 0 ; }
Find the remainder when N is divided by 4 using Bitwise AND operator | C implementation to find N modulo 4 using Bitwise AND operator ; Function to find the remainder ; Bitwise AND with 3 ; return x ; Driver code
#include <stdio.h> NEW_LINE int findRemainder ( int n ) { int x = n & 3 ; return x ; } int main ( ) { int N = 43 ; int ans = findRemainder ( N ) ; printf ( " % d " , ans ) ; return 0 ; }
Program to print triangular number series till n | C Program to find Triangular Number Series ; Function to find triangular number ; For each iteration increase j by 1 and add it into k ; Increasing j by 1 ; Add value of j into k and update k ; Driven Function
#include <stdio.h> NEW_LINE void triangular_series ( int n ) { int i , j = 1 , k = 1 ; for ( i = 1 ; i <= n ; i ++ ) { printf ( " ▁ % d ▁ " , k ) ; j = j + 1 ; k = k + j ; } } int main ( ) { int n = 5 ; triangular_series ( n ) ; return 0 ; }
Program to count digits in an integer ( 4 Different Methods ) | Recursive C program to count number of digits in a number ; Driver code
#include <stdio.h> NEW_LINE int countDigit ( long long n ) { if ( n / 10 == 0 ) return 1 ; return 1 + countDigit ( n / 10 ) ; } int main ( void ) { long long n = 345289467 ; printf ( " Number ▁ of ▁ digits ▁ : ▁ % d " , countDigit ( n ) ) ; return 0 ; }
Check if a number is magic ( Recursive sum of digits is 1 ) | C program to check Whether the number is Magic or not . ; Accepting sample input ; Condition to check Magic number
#include <stdio.h> NEW_LINE int main ( ) { int x = 1234 ; if ( x % 9 == 1 ) printf ( " Magic ▁ Number " ) ; else printf ( " Not ▁ a ▁ Magic ▁ Number " ) ; return 0 ; }
Interesting facts about Fibonacci numbers | C program to demonstrate that Fibonacci numbers that are divisible by their indexes have indexes as either power of 5 or multiple of 12. ; storing Fibonacci numbers
#include <stdio.h> NEW_LINE #define MAX 100 NEW_LINE int main ( ) { long long int arr [ MAX ] ; arr [ 0 ] = 0 ; arr [ 1 ] = 1 ; for ( int i = 2 ; i < MAX ; i ++ ) arr [ i ] = arr [ i - 1 ] + arr [ i - 2 ] ; printf ( " Fibonacci ▁ numbers ▁ divisible ▁ by ▁ " " their ▁ indexes ▁ are ▁ : STRNEWLINE " ) ; for ( int i = 1 ; i < MAX ; i ++ ) if ( arr [ i ] % i == 0 ) printf ( " % d ▁ " , i ) ; }
Maximum value of an integer for which factorial can be calculated on a machine | C program to find maximum value of an integer for which factorial can be calculated on your system ; when fact crosses its size , it gives negative value ; Driver Code
#include <stdio.h> NEW_LINE int findMaxValue ( ) { int res = 2 ; long long int fact = 2 ; while ( 1 ) { if ( fact < 0 ) break ; res ++ ; fact = fact * res ; } return res - 1 ; } int main ( ) { printf ( " Maximum ▁ value ▁ of ▁ integer ▁ : ▁ % d STRNEWLINE " , findMaxValue ( ) ) ; return 0 ; }
Given a number n , find the first k digits of n ^ n | C ++ program to generate first k digits of n ^ n ; function to calculate first k digits of n ^ n ; take log10 of n ^ n . log10 ( n ^ n ) = n * log10 ( n ) ; We now try to separate the decimal and integral part of the / product . The floor function returns the smallest integer less than or equal to the argument . So in this case , product - floor ( product ) will give us the decimal part of product ; we now exponentiate this back by raising 10 to the power of decimal part ; We now try to find the power of 10 by which we will have to multiply the decimal part to obtain our final answer ; driver function
#include <bits/stdc++.h> NEW_LINE using namespace std ; long long firstkdigits ( int n , int k ) { long double product = n * log10 ( n ) ; long double decimal_part = product - floor ( product ) ; decimal_part = pow ( 10 , decimal_part ) ; long long digits = pow ( 10 , k - 1 ) , i = 0 ; return decimal_part * digits ; } int main ( ) { int n = 1450 ; int k = 6 ; cout << firstkdigits ( n , k ) ; return 0 ; }
Multiply large integers under large modulo | C program of finding modulo multiplication ; Returns ( a * b ) % mod ; Update a if it is more than or equal to mod ; If b is odd , add a with result ; Here we assume that doing 2 * a doesn 't cause overflow ; b >>= 1 ; b = b / 2 ; Driver program
#include <stdio.h> NEW_LINE long long moduloMultiplication ( long long a , long long b , long long mod ) { a %= mod ; while ( b ) { if ( b & 1 ) res = ( res + a ) % mod ; a = ( 2 * a ) % mod ; } return res ; } int main ( ) { long long a = 10123465234878998 ; long long b = 65746311545646431 ; long long m = 10005412336548794 ; printf ( " % lld " , moduloMultiplication ( a , b , m ) ) ; return 0 ; }
Check if a number can be expressed as a sum of consecutive numbers | ; Updating n with 2 n ; ( n & ( n - 1 ) ) = > Checking whether we can write 2 n as 2 ^ k if yes ( can 't represent 2n as 2^k) then answer 1 if no (can represent 2n as 2^k) then answer 0
#include <stdio.h> NEW_LINE long long int canBeSumofConsec ( long long int n ) { n = 2 * n ; return ( ( n & ( n - 1 ) ) != 0 ) ; } int main ( ) { long long int n = 10 ; printf ( " % lld " , canBeSumofConsec ( n ) ) ; }
Combinatorial Game Theory | Set 2 ( Game of Nim ) | A C program to implement Game of Nim . The program assumes that both players are playing optimally ; A Structure to hold the two parameters of a move A move has two parameters - 1 ) pile_index = The index of pile from which stone is going to be removed 2 ) stones_removed = Number of stones removed from the pile indexed = pile_index ; A C function to output the current game state . ; A C function that returns True if game has ended and False if game is not yet over ; A C function to declare the winner of the game ; A C function to calculate the Nim - Sum at any point of the game . ; A C function to make moves of the Nim Game ; The player having the current turn is on a winning position . So he / she / it play optimally and tries to make Nim - Sum as 0 ; If this is not an illegal move then make this move . ; If you want to input yourself then remove the rand ( ) functions and modify the code to take inputs . But remember , you still won 't be able to change your fate/prediction. ; Create an array to hold indices of non - empty piles ; A C function to play the Game of Nim ; Driver program to test above functions ; Test Case 1 ; We will predict the results before playing The COMPUTER starts first ; Let us play the game with COMPUTER starting first and check whether our prediction was right or not ; Test Case 2 int piles [ ] = { 3 , 4 , 7 } ; int n = sizeof ( piles ) / sizeof ( piles [ 0 ] ) ; We will predict the results before playing The HUMAN ( You ) starts first ; Let us play the game with COMPUTER starting first and check whether our prediction was right or not playGame ( piles , n , HUMAN ) ;
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE #include <stdbool.h> NEW_LINE #define COMPUTER 1 NEW_LINE #define HUMAN 2 NEW_LINE struct move { int pile_index ; int stones_removed ; } ; void showPiles ( int piles [ ] , int n ) { int i ; printf ( " Current ▁ Game ▁ Status ▁ - > ▁ " ) ; for ( i = 0 ; i < n ; i ++ ) printf ( " % d ▁ " , piles [ i ] ) ; printf ( " STRNEWLINE " ) ; return ; } bool gameOver ( int piles [ ] , int n ) { int i ; for ( i = 0 ; i < n ; i ++ ) if ( piles [ i ] != 0 ) return ( false ) ; return ( true ) ; } void declareWinner ( int whoseTurn ) { if ( whoseTurn == COMPUTER ) printf ( " HUMAN won " else printf ( " COMPUTER won " return ; } int calculateNimSum ( int piles [ ] , int n ) { int i , nimsum = piles [ 0 ] ; for ( i = 1 ; i < n ; i ++ ) nimsum = nimsum ^ piles [ i ] ; return ( nimsum ) ; } void makeMove ( int piles [ ] , int n , struct move * moves ) { int i , nim_sum = calculateNimSum ( piles , n ) ; if ( nim_sum != 0 ) { for ( i = 0 ; i < n ; i ++ ) { if ( ( piles [ i ] ^ nim_sum ) < piles [ i ] ) { ( * moves ) . pile_index = i ; ( * moves ) . stones_removed = piles [ i ] - ( piles [ i ] ^ nim_sum ) ; piles [ i ] = ( piles [ i ] ^ nim_sum ) ; break ; } } } else { int non_zero_indices [ n ] , count ; for ( i = 0 , count = 0 ; i < n ; i ++ ) if ( piles [ i ] > 0 ) non_zero_indices [ count ++ ] = i ; ( * moves ) . pile_index = ( rand ( ) % ( count ) ) ; ( * moves ) . stones_removed = 1 + ( rand ( ) % ( piles [ ( * moves ) . pile_index ] ) ) ; piles [ ( * moves ) . pile_index ] = piles [ ( * moves ) . pile_index ] - ( * moves ) . stones_removed ; if ( piles [ ( * moves ) . pile_index ] < 0 ) piles [ ( * moves ) . pile_index ] = 0 ; } return ; } void playGame ( int piles [ ] , int n , int whoseTurn ) { printf ( " GAME STARTS " struct move moves ; while ( gameOver ( piles , n ) == false ) { showPiles ( piles , n ) ; makeMove ( piles , n , & moves ) ; if ( whoseTurn == COMPUTER ) { printf ( " COMPUTER ▁ removes ▁ % d ▁ stones ▁ from ▁ pile ▁ " " at ▁ index ▁ % d STRNEWLINE " , moves . stones_removed , moves . pile_index ) ; whoseTurn = HUMAN ; } else { printf ( " HUMAN ▁ removes ▁ % d ▁ stones ▁ from ▁ pile ▁ at ▁ " " index ▁ % d STRNEWLINE " , moves . stones_removed , moves . pile_index ) ; whoseTurn = COMPUTER ; } } showPiles ( piles , n ) ; declareWinner ( whoseTurn ) ; return ; } void knowWinnerBeforePlaying ( int piles [ ] , int n , int whoseTurn ) { printf ( " Prediction ▁ before ▁ playing ▁ the ▁ game ▁ - > ▁ " ) ; if ( calculateNimSum ( piles , n ) != 0 ) { if ( whoseTurn == COMPUTER ) printf ( " COMPUTER ▁ will ▁ win STRNEWLINE " ) ; else printf ( " HUMAN ▁ will ▁ win STRNEWLINE " ) ; } else { if ( whoseTurn == COMPUTER ) printf ( " HUMAN ▁ will ▁ win STRNEWLINE " ) ; else printf ( " COMPUTER ▁ will ▁ win STRNEWLINE " ) ; } return ; } int main ( ) { int piles [ ] = { 3 , 4 , 5 } ; int n = sizeof ( piles ) / sizeof ( piles [ 0 ] ) ; knowWinnerBeforePlaying ( piles , n , COMPUTER ) ; playGame ( piles , n , COMPUTER ) ; knowWinnerBeforePlaying ( piles , n , COMPUTER ) ; return ( 0 ) ; }
Program to find the Roots of Quadratic equation | C program to find roots of a quadratic equation ; Prints roots of quadratic equation ax * 2 + bx + x ; If a is 0 , then equation is not quadratic , but linear ; else d < 0 ; Driver code ; Function call
#include <math.h> NEW_LINE #include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE void findRoots ( int a , int b , int c ) { if ( a == 0 ) { printf ( " Invalid " ) ; return ; } int d = b * b - 4 * a * c ; double sqrt_val = sqrt ( abs ( d ) ) ; if ( d > 0 ) { printf ( " Roots ▁ are ▁ real ▁ and ▁ different ▁ STRNEWLINE " ) ; printf ( " % f % f " , ( double ) ( - b + sqrt_val ) / ( 2 * a ) , ( double ) ( - b - sqrt_val ) / ( 2 * a ) ) ; } else if ( d == 0 ) { printf ( " Roots ▁ are ▁ real ▁ and ▁ same ▁ STRNEWLINE " ) ; printf ( " % f " , - ( double ) b / ( 2 * a ) ) ; } { printf ( " Roots ▁ are ▁ complex ▁ STRNEWLINE " ) ; printf ( " % f ▁ + ▁ i % f % f - i % f " , - ( double ) b / ( 2 * a ) , sqrt_val / ( 2 * a ) , - ( double ) b / ( 2 * a ) , sqrt_val / ( 2 * a ) ; } } int main ( ) { int a = 1 , b = -7 , c = 12 ; findRoots ( a , b , c ) ; return 0 ; }
Convert from any base to decimal and vice versa | C program to convert a number from any base to decimal ; To return value of a char . For example , 2 is returned for '2' . 10 is returned for ' A ' , 11 for ' B ' ; Function to convert a number from given base ' b ' to decimal ; Initialize power of base ; Initialize result ; Decimal equivalent is str [ len - 1 ] * 1 + str [ len - 2 ] * base + str [ len - 3 ] * ( base ^ 2 ) + ... ; A digit in input number must be less than number 's base ; Driver code
#include <stdio.h> NEW_LINE #include <string.h> NEW_LINE int val ( char c ) { if ( c >= '0' && c <= '9' ) return ( int ) c - '0' ; else return ( int ) c - ' A ' + 10 ; } int toDeci ( char * str , int base ) { int len = strlen ( str ) ; int power = 1 ; int num = 0 ; int i ; for ( i = len - 1 ; i >= 0 ; i -- ) { if ( val ( str [ i ] ) >= base ) { printf ( " Invalid ▁ Number " ) ; return -1 ; } num += val ( str [ i ] ) * power ; power = power * base ; } return num ; } int main ( ) { char str [ ] = "11A " ; int base = 16 ; printf ( " Decimal ▁ equivalent ▁ of ▁ % s ▁ in ▁ base ▁ % d ▁ is ▁ " " ▁ % d STRNEWLINE " , str , base , toDeci ( str , base ) ) ; return 0 ; }
Solving f ( n ) = ( 1 ) + ( 2 * 3 ) + ( 4 * 5 * 6 ) . . . n using Recursion | C Program to print the solution of the series f ( n ) = ( 1 ) + ( 2 * 3 ) + ( 4 * 5 * 6 ) . . . n using recursion ; Recursive function for finding sum of series calculated - number of terms till which sum of terms has been calculated current - number of terms for which sum has to becalculated N - Number of terms in the function to be calculated ; checking termination condition ; product of terms till current ; recursive call for adding terms next in the series ; Driver Code ; input number of terms in the series ; invoking the function to calculate the sum
#include <stdio.h> NEW_LINE int seriesSum ( int calculated , int current , int N ) { int i , cur = 1 ; if ( current == N + 1 ) return 0 ; for ( i = calculated ; i < calculated + current ; i ++ ) cur *= i ; return cur + seriesSum ( i , current + 1 , N ) ; } int main ( ) { int N = 5 ; printf ( " % d STRNEWLINE " , seriesSum ( 1 , 1 , N ) ) ; return 0 ; }
Fibonacci Coding | C program for Fibonacci Encoding of a positive integer n ; To limit on the largest Fibonacci number to be used ; Array to store fibonacci numbers . fib [ i ] is going to store ( i + 2 ) 'th Fibonacci number ; Stores values in fib and returns index of the largest fibonacci number smaller than n . ; Fib [ 0 ] stores 2 nd Fibonacci No . ; Fib [ 1 ] stores 3 rd Fibonacci No . ; Keep Generating remaining numbers while previously generated number is smaller ; Return index of the largest fibonacci number smaller than or equal to n . Note that the above loop stopped when fib [ i - 1 ] became larger . ; Returns pointer to the char string which corresponds to code for n ; allocate memory for codeword ; index of the largest Fibonacci f <= n ; Mark usage of Fibonacci f ( 1 bit ) ; Subtract f from n ; Move to Fibonacci just smaller than f ; Mark all Fibonacci > n as not used ( 0 bit ) , progress backwards ; additional '1' bit ; return pointer to codeword ; driver function
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE #define N 30 NEW_LINE int fib [ N ] ; int largestFiboLessOrEqual ( int n ) { fib [ 0 ] = 1 ; fib [ 1 ] = 2 ; int i ; for ( i = 2 ; fib [ i - 1 ] <= n ; i ++ ) fib [ i ] = fib [ i - 1 ] + fib [ i - 2 ] ; return ( i - 2 ) ; } char * fibonacciEncoding ( int n ) { int index = largestFiboLessOrEqual ( n ) ; char * codeword = ( char * ) malloc ( sizeof ( char ) * ( index + 3 ) ) ; int i = index ; while ( n ) { codeword [ i ] = '1' ; n = n - fib [ i ] ; i = i - 1 ; while ( i >= 0 && fib [ i ] > n ) { codeword [ i ] = '0' ; i = i - 1 ; } } codeword [ index + 1 ] = '1' ; codeword [ index + 2 ] = ' \0' ; return codeword ; } int main ( ) { int n = 143 ; printf ( " Fibonacci ▁ code ▁ word ▁ for ▁ % d ▁ is ▁ % s STRNEWLINE " , n , fibonacciEncoding ( n ) ) ; return 0 ; }
Count number of squares in a rectangle | C program to count squares in a rectangle of size m x n ; Returns count of all squares in a rectangle of size m x n ; If n is smaller , swap m and n ; Now n is greater dimension , apply formula ; Driver Code
#include <stdio.h> NEW_LINE int countSquares ( int m , int n ) { if ( n < m ) { int temp = m ; m = n ; n = temp ; } return n * ( n + 1 ) * ( 3 * m - n + 1 ) / 6 ; } int main ( ) { int m = 4 , n = 3 ; printf ( " Count ▁ of ▁ squares ▁ is ▁ % d " , countSquares ( m , n ) ) ; }
Segmented Sieve | This functions finds all primes smaller than ' limit ' using simple sieve of eratosthenes . ; Create a boolean array " mark [ 0 . . limit - 1 ] " and initialize all entries of it as true . A value in mark [ p ] will finally be false if ' p ' is Not a prime , else true . ; One by one traverse all numbers so that their multiples can be marked as composite . ; If p is not changed , then it is a prime ; Update all multiples of p ; Print all prime numbers and store them in prime
void simpleSieve ( int limit ) { bool mark [ limit ] ; for ( int i = 0 ; i < limit ; i ++ ) { mark [ i ] = true ; } for ( int p = 2 ; p * p < limit ; p ++ ) { if ( mark [ p ] == true ) { for ( int i = p * p ; i < limit ; i += p ) mark [ i ] = false ; } } for ( int p = 2 ; p < limit ; p ++ ) if ( mark [ p ] == true ) cout << p << " ▁ " ; }
Modular multiplicative inverse | Iterative C program to find modular inverse using extended Euclid algorithm ; Returns modulo inverse of a with respect to m using extended Euclid Algorithm Assumption : a and m are coprimes , i . e . , gcd ( a , m ) = 1 ; q is quotient ; m is remainder now , process same as Euclid 's algo ; Update y and x ; Make x positive ; Driver Code ; Function call
#include <stdio.h> NEW_LINE int modInverse ( int a , int m ) { int m0 = m ; int y = 0 , x = 1 ; if ( m == 1 ) return 0 ; while ( a > 1 ) { int q = a / m ; int t = m ; m = a % m , a = t ; t = y ; y = x - q * y ; x = t ; } if ( x < 0 ) x += m0 ; return x ; } int main ( ) { int a = 3 , m = 11 ; printf ( " Modular ▁ multiplicative ▁ inverse ▁ is ▁ % d STRNEWLINE " , modInverse ( a , m ) ) ; return 0 ; }
Euler 's Totient Function | A simple C program to calculate Euler 's Totient Function ; Function to return gcd of a and b ; A simple method to evaluate Euler Totient Function ; Driver program to test above function
#include <stdio.h> NEW_LINE int gcd ( int a , int b ) { if ( a == 0 ) return b ; return gcd ( b % a , a ) ; } int phi ( unsigned int n ) { unsigned int result = 1 ; for ( int i = 2 ; i < n ; i ++ ) if ( gcd ( i , n ) == 1 ) result ++ ; return result ; } int main ( ) { int n ; for ( n = 1 ; n <= 10 ; n ++ ) printf ( " phi ( % d ) ▁ = ▁ % d STRNEWLINE " , n , phi ( n ) ) ; return 0 ; }
Euler 's Totient Function | C program to calculate Euler ' s ▁ Totient ▁ Function ▁ using ▁ Euler ' s product formula ; Consider all prime factors of n and for every prime factor p , multiply result with ( 1 - 1 / p ) ; Check if p is a prime factor . ; If yes , then update n and result ; If n has a prime factor greater than sqrt ( n ) ( There can be at - most one such prime factor ) ; Driver program to test above function
#include <stdio.h> NEW_LINE int phi ( int n ) { for ( int p = 2 ; p * p <= n ; ++ p ) { if ( n % p == 0 ) { while ( n % p == 0 ) n /= p ; result *= ( 1.0 - ( 1.0 / ( float ) p ) ) ; } } if ( n > 1 ) result *= ( 1.0 - ( 1.0 / ( float ) n ) ) ; return ( int ) result ; } int main ( ) { int n ; for ( n = 1 ; n <= 10 ; n ++ ) printf ( " phi ( % d ) ▁ = ▁ % d STRNEWLINE " , n , phi ( n ) ) ; return 0 ; }
Program to print first n Fibonacci Numbers | Set 1 | C program to print first n Fibonacci numbers ; Function to print first n Fibonacci Numbers ; Driver Code
#include <stdio.h> NEW_LINE void printFibonacciNumbers ( int n ) { int f1 = 0 , f2 = 1 , i ; if ( n < 1 ) return ; printf ( " % d ▁ " , f1 ) ; for ( i = 1 ; i < n ; i ++ ) { printf ( " % d ▁ " , f2 ) ; int next = f1 + f2 ; f1 = f2 ; f2 = next ; } } int main ( ) { printFibonacciNumbers ( 7 ) ; return 0 ; }
Program to find LCM of two numbers | C program to find LCM of two numbers ; Recursive function to return gcd of a and b ; Function to return LCM of two numbers ; Driver program to test above function
#include <stdio.h> NEW_LINE int gcd ( int a , int b ) { if ( a == 0 ) return b ; return gcd ( b % a , a ) ; } int lcm ( int a , int b ) { return ( a / gcd ( a , b ) ) * b ; } int main ( ) { int a = 15 , b = 20 ; printf ( " LCM ▁ of ▁ % d ▁ and ▁ % d ▁ is ▁ % d ▁ " , a , b , lcm ( a , b ) ) ; return 0 ; }
Program to convert a given number to words | C program to print a given number in words . The program handles numbers from 0 to 9999 ; A function that prints given number in words ; Base cases ; The first string is not used , it is to make array indexing simple ; The first string is not used , it is to make array indexing simple ; The first two string are not used , they are to make array indexing simple ; Used for debugging purpose only ; For single digit number ; Iterate while num is not ' \0' ; Code path for first 2 digits ; tens_power [ len - 3 ] ) ; here len can be 3 or 4 ; Code path for last 2 digits ; Need to explicitly handle 10 - 19. Sum of the two digits is used as index of " two _ digits " array of strings ; Need to explicitely handle 20 ; Rest of the two digit numbers i . e . , 21 to 99 ; Driver program to test above function
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE #include <string.h> NEW_LINE void convert_to_words ( char * num ) { int len = strlen ( if ( len == 0 ) { fprintf ( stderr , " empty ▁ string STRNEWLINE " ) ; return ; } if ( len > 4 ) { fprintf ( stderr , " Length ▁ more ▁ than ▁ 4 ▁ is ▁ not ▁ supported STRNEWLINE " ) ; return ; } char * single_digits [ ] = { " zero " , " one " , " two " , " three " , " four " , " five " , " six " , " seven " , " eight " , " nine " } ; char * two_digits [ ] = { " " , " ten " , " eleven " , " twelve " , " thirteen " , " fourteen " , " fifteen " , " sixteen " , " seventeen " , " eighteen " , " nineteen " } ; char * tens_multiple [ ] = { " " , " " , " twenty " , " thirty " , " forty " , " fifty " , " sixty " , " seventy " , " eighty " , " ninety " } ; char * tens_power [ ] = { " hundred " , " thousand " } ; printf ( " % s : " , num ) ; if ( len == 1 ) { printf ( " % s STRNEWLINE " , single_digits [ * num - '0' ] ) ; return ; } while ( * num != ' \0' ) { if ( len >= 3 ) { if ( * num - '0' != 0 ) { printf ( " % s ▁ " , single_digits [ * num - '0' ] ) ; printf ( " % s ▁ " , } -- len ; } else { if ( * num == '1' ) { int sum = * num - '0' + * ( num + 1 ) - '0' ; printf ( " % s STRNEWLINE " , two_digits [ sum ] ) ; return ; } else if ( * num == '2' && * ( num + 1 ) == '0' ) { printf ( " twenty STRNEWLINE " ) ; return ; } else { int i = * num - '0' ; printf ( " % s ▁ " , i ? tens_multiple [ i ] : " " ) ; ++ num ; if ( * num != '0' ) printf ( " % s ▁ " , single_digits [ * num - '0' ] ) ; } } ++ num ; } } int main ( void ) { convert_to_words ( "9923" ) ; convert_to_words ( "523" ) ; convert_to_words ( "89" ) ; convert_to_words ( "8" ) ; return 0 ; }
To find sum of two numbers without using any operator | ; Driver code
#include <stdio.h> NEW_LINE int add ( int x , int y ) { return printf ( " % * c % * c " , x , ' ▁ ' , y , ' ▁ ' ) ; } int main ( ) { printf ( " Sum ▁ = ▁ % d " , add ( 3 , 4 ) ) ; return 0 ; }
Check if a number is multiple of 5 without using / and % operators | Assuming that integer takes 4 bytes , there can be maximum 10 digits in a integer ; Check the last character of string ; Driver Code
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE #include <string.h> NEW_LINE # define MAX 11 NEW_LINE bool isMultipleof5 ( int n ) { char str [ MAX ] ; int len = strlen ( str ) ; if ( str [ len - 1 ] == '5' str [ len - 1 ] == '0' ) return true ; return false ; } int main ( ) { int n = 19 ; if ( isMultipleof5 ( n ) == true ) printf ( " % d ▁ is ▁ multiple ▁ of ▁ 5 STRNEWLINE " , n ) ; else printf ( " % d ▁ is ▁ not ▁ a ▁ multiple ▁ of ▁ 5 STRNEWLINE " , n ) ; return 0 ; }
XOR Linked List | C program to implement the above approach ; Structure of a node in XOR linked list ; Stores data value of a node ; Stores XOR of previous pointer and next pointer ; Function to find the XOR of address of two nodes ; Function to insert a node with given value at given position ; If XOR linked list is empty ; Initialize a new Node ; Stores data value in the node ; Stores XOR of previous and next pointer ; Update pointer of head node ; If the XOR linked list is not empty ; Stores the address of current node ; Stores the address of previous node ; Initialize a new Node ; Update curr node address ; Update new node address ; Update head ; Update data value of current node ; Function to print elements of the XOR Linked List ; Stores XOR pointer in current node ; Stores XOR pointer of in previous Node ; Stores XOR pointer of in next node ; Traverse XOR linked list ; Print current node ; Forward traversal ; Update prev ; Update curr ; Reverse the linked list in group of K ; Stores head node ; If the XOR linked list is empty ; Stores count of nodes reversed in current group ; Stores XOR pointer of in previous Node ; Stores XOR pointer of in next node ; Reverse nodes in current group ; Forward traversal ; Update prev ; Update curr ; Update count ; Disconnect prev node from the next node ; Disconnect curr from previous node ; If the count of remaining nodes is less than K ; Update len ; Recursively process the next nodes ; Connect the head pointer with the prev ; Connect prev with the head ; Driver Code ; Create following XOR Linked List head -- > 7 < a > 6 < a > 8 < a > 11 < a > 3 < a > 1 < a > 2 < a > 0 ; Function Call ; Print the reversed list
#include <inttypes.h> NEW_LINE #include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE struct Node { int data ; struct Node * nxp ; } ; struct Node * XOR ( struct Node * a , struct Node * b ) { return ( struct Node * ) ( ( uintptr_t ) ( a ) ^ ( uintptr_t ) ( b ) ) ; } struct Node * insert ( struct Node * * head , int value ) { if ( * head == NULL ) { struct Node * node = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; node -> data = value ; node -> nxp = XOR ( NULL , NULL ) ; * head = node ; } else { struct Node * curr = * head ; struct Node * prev = NULL ; struct Node * node = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; curr -> nxp = XOR ( node , XOR ( NULL , curr -> nxp ) ) ; node -> nxp = XOR ( NULL , curr ) ; * head = node ; node -> data = value ; } return * head ; } void printList ( struct Node * * head ) { struct Node * curr = * head ; struct Node * prev = NULL ; struct Node * next ; while ( curr != NULL ) { printf ( " % d ▁ " , curr -> data ) ; next = XOR ( prev , curr -> nxp ) ; prev = curr ; curr = next ; } } struct Node * RevInGrp ( struct Node * * head , int K , int len ) { struct Node * curr = * head ; if ( curr == NULL ) return NULL ; int count = 0 ; struct Node * prev = NULL ; struct Node * next ; while ( count < K && count < len ) { next = XOR ( prev , curr -> nxp ) ; prev = curr ; curr = next ; count ++ ; } prev -> nxp = XOR ( NULL , XOR ( prev -> nxp , curr ) ) ; if ( curr != NULL ) curr -> nxp = XOR ( XOR ( curr -> nxp , prev ) , NULL ) ; if ( len < K ) { return prev ; } else { len -= K ; struct Node * dummy = RevInGrp ( & curr , K , len ) ; ( * head ) -> nxp = XOR ( XOR ( NULL , ( * head ) -> nxp ) , dummy ) ; if ( dummy != NULL ) dummy -> nxp = XOR ( XOR ( dummy -> nxp , NULL ) , * head ) ; return prev ; } } int main ( ) { struct Node * head = NULL ; insert ( & head , 0 ) ; insert ( & head , 2 ) ; insert ( & head , 1 ) ; insert ( & head , 3 ) ; insert ( & head , 11 ) ; insert ( & head , 8 ) ; insert ( & head , 6 ) ; insert ( & head , 7 ) ; head = RevInGrp ( & head , 3 , 8 ) ; printList ( & head ) ; return ( 0 ) ; }
XOR Linked List | C program for the above approach ; Structure of a node in XOR linked list ; Stores data value of a node ; Stores XOR of previous pointer and next pointer ; Function to find the XOR of two nodes ; Function to insert a node with given value at beginning position ; If XOR linked list is empty ; Initialize a new Node ; Stores data value in the node ; Stores XOR of previous and next pointer ; Update pointer of head node ; If the XOR linked list is not empty ; Stores the address of current node ; Stores the address of previous node ; Initialize a new Node ; Update curr node address ; Update new node address ; Update head ; Update data value of current node ; Function to print elements of the XOR Linked List ; Stores XOR pointer in current node ; Stores XOR pointer of in previous Node ; Stores XOR pointer of in next node ; Traverse XOR linked list ; Print current node ; Forward traversal ; Update prev ; Update curr ; Function to reverse the XOR linked list ; Stores XOR pointer in current node ; Stores XOR pointer of in previous Node ; Stores XOR pointer of in next node ; Forward traversal ; Update prev ; Update curr ; Update the head pointer ; Driver Code ; Create following XOR Linked List head -- > 40 < -- > 30 < -- > 20 < -- > 10 ; Reverse the XOR Linked List to give head -- > 10 < -- > 20 < -- > 30 < -- > 40
#include <inttypes.h> NEW_LINE #include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE struct Node { int data ; struct Node * nxp ; } ; struct Node * XOR ( struct Node * a , struct Node * b ) { return ( struct Node * ) ( ( uintptr_t ) ( a ) ^ ( uintptr_t ) ( b ) ) ; } struct Node * insert ( struct Node * * head , int value ) { if ( * head == NULL ) { struct Node * node = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; node -> data = value ; node -> nxp = XOR ( NULL , NULL ) ; * head = node ; } else { struct Node * curr = * head ; struct Node * prev = NULL ; struct Node * node = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; curr -> nxp = XOR ( node , XOR ( NULL , curr -> nxp ) ) ; node -> nxp = XOR ( NULL , curr ) ; * head = node ; node -> data = value ; } return * head ; } void printList ( struct Node * * head ) { struct Node * curr = * head ; struct Node * prev = NULL ; struct Node * next ; while ( curr != NULL ) { printf ( " % d ▁ " , curr -> data ) ; next = XOR ( prev , curr -> nxp ) ; prev = curr ; curr = next ; } printf ( " STRNEWLINE " ) ; } struct Node * reverse ( struct Node * * head ) { struct Node * curr = * head ; if ( curr == NULL ) return NULL ; else { struct Node * prev = NULL ; struct Node * next ; while ( XOR ( prev , curr -> nxp ) != NULL ) { next = XOR ( prev , curr -> nxp ) ; prev = curr ; curr = next ; } * head = curr ; return * head ; } } int main ( ) { struct Node * head = NULL ; insert ( & head , 10 ) ; insert ( & head , 20 ) ; insert ( & head , 30 ) ; insert ( & head , 40 ) ; printf ( " XOR ▁ linked ▁ list : ▁ " ) ; printList ( & head ) ; reverse ( & head ) ; printf ( " Reversed ▁ XOR ▁ linked ▁ list : ▁ " ) ; printList ( & head ) ; return ( 0 ) ; }
XOR Linked List | C program to implement the above approach ; Structure of a node in XOR linked list ; Stores data value of a node ; Stores XOR of previous pointer and next pointer ; Function to find the XOR of two nodes ; Function to insert a node with given value at given position ; If XOR linked list is empty ; Initialize a new Node ; Stores data value in the node ; Stores XOR of previous and next pointer ; Update pointer of head node ; If the XOR linked list is not empty ; Stores the address of current node ; Stores the address of previous node ; Initialize a new Node ; Update curr node address ; Update new node address ; Update head ; Update data value of current node ; Function to print elements of the XOR Linked List ; Stores XOR pointer in current node ; Stores XOR pointer of in previous Node ; Stores XOR pointer of in next node ; Traverse XOR linked list ; Print current node ; Forward traversal ; Update prev ; Update curr ; Stores XOR pointer in current node ; Stores XOR pointer of in previous Node ; Stores XOR pointer of in next node ; Forward traversal ; Update prev ; Update curr ; Forward traversal ; Update prev ; Update curr ; Driver Code ; Create following XOR Linked List head -- > 7 a > 6 a > 8 a > 11 a > 3 a > 1 a > 2 a > 0
#include <inttypes.h> NEW_LINE #include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE struct Node { int data ; struct Node * nxp ; } ; struct Node * XOR ( struct Node * a , struct Node * b ) { return ( struct Node * ) ( ( uintptr_t ) ( a ) ^ ( uintptr_t ) ( b ) ) ; } struct Node * insert ( struct Node * * head , int value ) { if ( * head == NULL ) { struct Node * node = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; node -> data = value ; node -> nxp = XOR ( NULL , NULL ) ; * head = node ; } else { struct Node * curr = * head ; struct Node * prev = NULL ; struct Node * node = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; curr -> nxp = XOR ( node , XOR ( NULL , curr -> nxp ) ) ; node -> nxp = XOR ( NULL , curr ) ; * head = node ; node -> data = value ; } return * head ; } void printList ( struct Node * * head ) { struct Node * curr = * head ; struct Node * prev = NULL ; struct Node * next ; while ( curr != NULL ) { printf ( " % d ▁ " , curr -> data ) ; next = XOR ( prev , curr -> nxp ) ; prev = curr ; curr = next ; } } struct Node * NthNode ( struct Node * * head , int N ) { int count = 0 ; struct Node * curr = * head ; struct Node * curr1 = * head ; struct Node * prev = NULL ; struct Node * prev1 = NULL ; struct Node * next ; struct Node * next1 ; while ( count < N && curr != NULL ) { next = XOR ( prev , curr -> nxp ) ; prev = curr ; curr = next ; count ++ ; } if ( curr == NULL && count < N ) { printf ( " Wrong ▁ Input " ) ; return ( uintptr_t ) 0 ; } else { while ( curr != NULL ) { next = XOR ( prev , curr -> nxp ) ; next1 = XOR ( prev1 , curr1 -> nxp ) ; prev = curr ; prev1 = curr1 ; curr = next ; curr1 = next1 ; } printf ( " % d " , curr1 -> data ) ; } } int main ( ) { struct Node * head = NULL ; insert ( & head , 0 ) ; insert ( & head , 2 ) ; insert ( & head , 1 ) ; insert ( & head , 3 ) ; insert ( & head , 11 ) ; insert ( & head , 8 ) ; insert ( & head , 6 ) ; insert ( & head , 7 ) ; NthNode ( & head , 3 ) ; return ( 0 ) ; }
XOR Linked List | C program to implement the above approach ; Structure of a node in XOR linked list ; Stores data value of a node ; Stores XOR of previous pointer and next pointer ; Function to find the XOR of two nodes ; Function to insert a node with given value at given position ; If XOR linked list is empty ; Initialize a new Node ; Stores data value in the node ; Stores XOR of previous and next pointer ; Update pointer of head node ; If the XOR linked list is not empty ; Stores the address of current node ; Stores the address of previous node ; Initialize a new Node ; Update curr node address ; Update new node address ; Update head ; Update data value of current node ; Function to print the middle node ; Stores XOR pointer in current node ; Stores XOR pointer of in previous Node ; Stores XOR pointer of in next node ; Traverse XOR linked list ; Forward traversal ; Update prev ; Update curr ; If the length of the linked list is odd ; If the length of the linked list is even ; Driver Code ; Create following XOR Linked List head -- > 4 a > 7 a > 5
#include <inttypes.h> NEW_LINE #include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE struct Node { int data ; struct Node * nxp ; } ; struct Node * XOR ( struct Node * a , struct Node * b ) { return ( struct Node * ) ( ( uintptr_t ) ( a ) ^ ( uintptr_t ) ( b ) ) ; } struct Node * insert ( struct Node * * head , int value ) { if ( * head == NULL ) { struct Node * node = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; node -> data = value ; node -> nxp = XOR ( NULL , NULL ) ; * head = node ; } else { struct Node * curr = * head ; struct Node * prev = NULL ; struct Node * node = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; curr -> nxp = XOR ( node , XOR ( NULL , curr -> nxp ) ) ; node -> nxp = XOR ( NULL , curr ) ; * head = node ; node -> data = value ; } return * head ; } int printMiddle ( struct Node * * head , int len ) { int count = 0 ; struct Node * curr = * head ; struct Node * prev = NULL ; struct Node * next ; int middle = ( int ) len / 2 ; while ( count != middle ) { next = XOR ( prev , curr -> nxp ) ; prev = curr ; curr = next ; count ++ ; } if ( len & 1 ) { printf ( " % d " , curr -> data ) ; } else { printf ( " % d ▁ % d " , prev -> data , curr -> data ) ; } } int main ( ) { struct Node * head = NULL ; insert ( & head , 4 ) ; insert ( & head , 7 ) ; insert ( & head , 5 ) ; printMiddle ( & head , 3 ) ; return ( 0 ) ; }
XOR Linked List | C ++ program to implement the above approach ; Structure of a node in XOR linked list ; Stores data value of a node ; Stores XOR of previous pointer and next pointer ; Function to find the XOR of two nodes ; Function to insert a node with given value at given position ; If XOR linked list is empty ; If given position is equal to 1 ; Initialize a new Node ; Stores data value in the node ; Stores XOR of previous and next pointer ; Update pointer of head node ; If required position was not found ; If the XOR linked list is not empty ; Stores position of a node in the XOR linked list ; Stores the address of current node ; Stores the address of previous node ; Stores the XOR of next node and previous node ; Traverse the XOR linked list ; Update prev ; Update curr ; Update next ; Update Pos ; If the position of the current node is equal to the given position ; Initialize a new Node ; Stores pointer to previous Node as ( prev ^ next ^ next ) = prev ; Stores XOR of prev and new node ; Connecting new node with next ; Update pointer of next ; Connect node with curr and next curr < -- node -- > next ; Insertion node at beginning ; Initialize a new Node ; Update curr node address ; Update new node address ; Update head ; Update data value of current node ; Function to print elements of the XOR Linked List ; Stores XOR pointer in current node ; Stores XOR pointer of in previous Node ; Stores XOR pointer of in next node ; Traverse XOR linked list ; Print current node ; Forward traversal ; Update prev ; Update curr ; Driver Code ; Create following XOR Linked List head -- > 20 < -- > 40 < -- > 10 < -- > 30 ; Print the new list
#include <inttypes.h> NEW_LINE #include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE struct Node { int data ; struct Node * nxp ; } ; struct Node * XOR ( struct Node * a , struct Node * b ) { return ( struct Node * ) ( ( uintptr_t ) ( a ) ^ ( uintptr_t ) ( b ) ) ; } struct Node * insert ( struct Node * * head , int value , int position ) { if ( * head == NULL ) { if ( position == 1 ) { struct Node * node = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; node -> data = value ; node -> nxp = XOR ( NULL , NULL ) ; * head = node ; } else { printf ( " Invalid ▁ Position STRNEWLINE " ) ; } } else { int Pos = 1 ; struct Node * curr = * head ; struct Node * prev = NULL ; struct Node * next = XOR ( prev , curr -> nxp ) ; while ( next != NULL && Pos < position - 1 ) { prev = curr ; curr = next ; next = XOR ( prev , curr -> nxp ) ; Pos ++ ; } if ( Pos == position - 1 ) { struct Node * node = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; struct Node * temp = XOR ( curr -> nxp , next ) ; curr -> nxp = XOR ( temp , node ) ; if ( next != NULL ) { next -> nxp = XOR ( node , XOR ( next -> nxp , curr ) ) ; } node -> nxp = XOR ( curr , next ) ; node -> data = value ; } else if ( position == 1 ) { struct Node * node = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; curr -> nxp = XOR ( node , XOR ( NULL , curr -> nxp ) ) ; node -> nxp = XOR ( NULL , curr ) ; * head = node ; node -> data = value ; } else { printf ( " Invalid ▁ Position STRNEWLINE " ) ; } } return * head ; } void printList ( struct Node * * head ) { struct Node * curr = * head ; struct Node * prev = NULL ; struct Node * next ; while ( curr != NULL ) { printf ( " % d ▁ " , curr -> data ) ; next = XOR ( prev , curr -> nxp ) ; prev = curr ; curr = next ; } } int main ( ) { struct Node * head = NULL ; insert ( & head , 10 , 1 ) ; insert ( & head , 20 , 1 ) ; insert ( & head , 30 , 3 ) ; insert ( & head , 40 , 2 ) ; printList ( & head ) ; return ( 0 ) ; }
Program to toggle K | C program to toggle K - th bit of a number N ; Function to toggle the kth bit of n ; Driver code
#include <stdio.h> NEW_LINE int toggleBit ( int n , int k ) { return ( n ^ ( 1 << ( k - 1 ) ) ) ; } int main ( ) { int n = 5 , k = 2 ; printf ( " % d STRNEWLINE " , toggleBit ( n , k ) ) ; return 0 ; }
Program to clear K | C program to clear K - th bit of a number N ; Function to clear the kth bit of n ; Driver code
#include <stdio.h> NEW_LINE int clearBit ( int n , int k ) { return ( n & ( ~ ( 1 << ( k - 1 ) ) ) ) ; } int main ( ) { int n = 5 , k = 1 ; printf ( " % d STRNEWLINE " , clearBit ( n , k ) ) ; return 0 ; }
Left Shift and Right Shift Operators in C / C ++ | C ++ Program to demonstrate use of right shift operator ; a = 5 ( 00000101 ) , b = 9 ( 00001001 ) ; The result is 00000010 ; The result is 00000100
#include <stdio.h> NEW_LINE using namespace std ; int main ( ) { unsigned char a = 5 , b = 9 ; printf ( " a > > 1 ▁ = ▁ % d STRNEWLINE " , a >> 1 ) ; printf ( " b > > 1 ▁ = ▁ % d STRNEWLINE " , b >> 1 ) ; return 0 ; }
Left Shift and Right Shift Operators in C / C ++ | ; shift y by 61 bits left
#include <stdio.h> NEW_LINE int main ( ) { int x = 19 ; unsigned long long y = 19 ; printf ( " x ▁ < < ▁ 1 ▁ = ▁ % d STRNEWLINE " , x << 1 ) ; printf ( " x ▁ > > ▁ 1 ▁ = ▁ % d STRNEWLINE " , x >> 1 ) ; printf ( " y ▁ < < ▁ 61 ▁ = ▁ % lld STRNEWLINE " , y << 61 ) ; return 0 ; }
Left Shift and Right Shift Operators in C / C ++ |
#include <stdio.h> NEW_LINE int main ( ) { int i = 3 ; printf ( " pow ( 2 , ▁ % d ) ▁ = ▁ % d STRNEWLINE " , i , 1 << i ) ; i = 4 ; printf ( " pow ( 2 , ▁ % d ) ▁ = ▁ % d STRNEWLINE " , i , 1 << i ) ; return 0 ; }
Bitwise recursive addition of two integers | C program to do recursive addition of two integers ; If bitwise & is 0 , then there is not going to be any carry . Hence result of XOR is addition . ; Driver code
#include <stdio.h> NEW_LINE int add ( int x , int y ) { int keep = ( x & y ) << 1 ; int res = x ^ y ; if ( keep == 0 ) return res ; add ( keep , res ) ; } int main ( ) { printf ( " % d " , add ( 15 , 38 ) ) ; return 0 ; }
Count total bits in a number | C program to find total bit in given number ; log function in base 2 take only integer part ; Driven program
#include <stdio.h> NEW_LINE #include <math.h> NEW_LINE unsigned countBits ( unsigned int number ) { return ( int ) log2 ( number ) + 1 ; } int main ( ) { unsigned int num = 65 ; printf ( " % d STRNEWLINE " , countBits ( num ) ) ; return 0 ; }
Find the n | Efficient C program to find n - th palindrome ; Construct the nth binary palindrome with the given group number , aux_number and operation type ; No need to insert any bit in the middle ; Length of the final binary representation ; Fill first and last bit as 1 ; Start filling the a [ ] from middle , with the aux_num binary representation ; Get the auxiliary number 's ith bit and fill around middle ; Insert bit 0 in the middle ; Length of the final binary representation ; Fill first and last bit as 1 ; Start filling the a [ ] from middle , with the aux_num binary representation ; Get the auxiliary number 's ith bit and fill around middle ; else Insert bit 1 in the middle ; Length of the final binary representation ; Fill first and last bit as 1 ; Start filling the a [ ] from middle , with the aux_num binary representation ; Get the auxiliary number 's ith bit and fill around middle ; Convert the number to decimal from binary ; Will return the nth binary palindrome number ; Add number of elements in all the groups , until the group of the nth number is found ; Total number of elements until this group ; Element 's offset position in the group ; Finding which bit to be placed in the middle and finding the number , which we will fill from the middle in both directions ; We need to fill this auxiliary number in binary form the middle in both directions ; op = 0 ; Need to Insert 0 at middle ; op = 1 ; Need to Insert 1 at middle ; Driver code ; Function Call
#include <stdio.h> NEW_LINE #define INT_SIZE 32 NEW_LINE int constructNthNumber ( int group_no , int aux_num , int op ) { int a [ INT_SIZE ] = { 0 } ; int num = 0 , len_f ; int i = 0 ; if ( op == 2 ) { len_f = 2 * group_no ; a [ len_f - 1 ] = a [ 0 ] = 1 ; while ( aux_num ) { a [ group_no + i ] = a [ group_no - 1 - i ] = aux_num & 1 ; aux_num = aux_num >> 1 ; i ++ ; } } else if ( op == 0 ) { len_f = 2 * group_no + 1 ; a [ len_f - 1 ] = a [ 0 ] = 1 ; a [ group_no ] = 0 ; while ( aux_num ) { a [ group_no + 1 + i ] = a [ group_no - 1 - i ] = aux_num & 1 ; aux_num = aux_num >> 1 ; i ++ ; } } { len_f = 2 * group_no + 1 ; a [ len_f - 1 ] = a [ 0 ] = 1 ; a [ group_no ] = 1 ; while ( aux_num ) { a [ group_no + 1 + i ] = a [ group_no - 1 - i ] = aux_num & 1 ; aux_num = aux_num >> 1 ; i ++ ; } } for ( i = 0 ; i < len_f ; i ++ ) num += ( 1 << i ) * a [ i ] ; return num ; } int getNthNumber ( int n ) { int group_no = 0 , group_offset ; int count_upto_group = 0 , count_temp = 1 ; int op , aux_num ; while ( count_temp < n ) { group_no ++ ; count_upto_group = count_temp ; count_temp += 3 * ( 1 << ( group_no - 1 ) ) ; } group_offset = n - count_upto_group - 1 ; if ( ( group_offset + 1 ) <= ( 1 << ( group_no - 1 ) ) ) { aux_num = group_offset ; } else { if ( ( ( group_offset + 1 ) - ( 1 << ( group_no - 1 ) ) ) % 2 ) else aux_num = ( ( group_offset ) - ( 1 << ( group_no - 1 ) ) ) / 2 ; } return constructNthNumber ( group_no , aux_num , op ) ; } int main ( ) { int n = 9 ; printf ( " % d " , getNthNumber ( n ) ) ; return 0 ; }
Toggle all the bits of a number except k | C program to toggle all bits except kth bit ; Returns a number with all bit toggled in n except k - th bit ; 1 ) Toggle k - th bit by doing n ^ ( 1 << k ) 2 ) Toggle all bits of the modified number ; Driver code
#include <stdio.h> NEW_LINE unsigned int toggleAllExceptK ( unsigned int n , unsigned int k ) { return ~ ( n ^ ( 1 << k ) ) ; } int main ( ) { unsigned int n = 4294967295 ; unsigned int k = 0 ; printf ( " % u " , toggleAllExceptK ( n , k ) ) ; return 0 ; }
Operators in C | Set 2 ( Relational and Logical Operators ) | C program to demonstrate working of relational operators ; greater than example ; greater than equal to ; less than example ; lesser than equal to ; equal to ; not equal to
#include <stdio.h> NEW_LINE int main ( ) { int a = 10 , b = 4 ; if ( a > b ) printf ( " a ▁ is ▁ greater ▁ than ▁ b STRNEWLINE " ) ; else printf ( " a ▁ is ▁ less ▁ than ▁ or ▁ equal ▁ to ▁ b STRNEWLINE " ) ; if ( a >= b ) printf ( " a ▁ is ▁ greater ▁ than ▁ or ▁ equal ▁ to ▁ b STRNEWLINE " ) ; else printf ( " a ▁ is ▁ lesser ▁ than ▁ b STRNEWLINE " ) ; if ( a < b ) printf ( " a ▁ is ▁ less ▁ than ▁ b STRNEWLINE " ) ; else printf ( " a ▁ is ▁ greater ▁ than ▁ or ▁ equal ▁ to ▁ b STRNEWLINE " ) ; if ( a <= b ) printf ( " a ▁ is ▁ lesser ▁ than ▁ or ▁ equal ▁ to ▁ b STRNEWLINE " ) ; else printf ( " a ▁ is ▁ greater ▁ than ▁ b STRNEWLINE " ) ; if ( a == b ) printf ( " a ▁ is ▁ equal ▁ to ▁ b STRNEWLINE " ) ; else printf ( " a ▁ and ▁ b ▁ are ▁ not ▁ equal STRNEWLINE " ) ; if ( a != b ) printf ( " a ▁ is ▁ not ▁ equal ▁ to ▁ b STRNEWLINE " ) ; else printf ( " a ▁ is ▁ equal ▁ b STRNEWLINE " ) ; return 0 ; }
Operators in C | Set 2 ( Relational and Logical Operators ) | C program to demonstrate working of logical operators ; logical AND example ; logical OR example ; logical NOT example
#include <stdio.h> NEW_LINE int main ( ) { int a = 10 , b = 4 , c = 10 , d = 20 ; if ( a > b && c == d ) printf ( " a ▁ is ▁ greater ▁ than ▁ b ▁ AND ▁ c ▁ is ▁ equal ▁ to ▁ d STRNEWLINE " ) ; else printf ( " AND ▁ condition ▁ not ▁ satisfied STRNEWLINE " ) ; if ( a > b c == d ) printf ( " a ▁ is ▁ greater ▁ than ▁ b ▁ OR ▁ c ▁ is ▁ equal ▁ to ▁ d STRNEWLINE " ) ; else printf ( " Neither ▁ a ▁ is ▁ greater ▁ than ▁ b ▁ nor ▁ c ▁ is ▁ equal ▁ " " ▁ to ▁ d STRNEWLINE " ) ; if ( ! a ) printf ( " a ▁ is ▁ zero STRNEWLINE " ) ; else printf ( " a ▁ is ▁ not ▁ zero " ) ; return 0 ; }
Operators in C | Set 2 ( Relational and Logical Operators ) |
#include <stdbool.h> NEW_LINE #include <stdio.h> NEW_LINE int main ( ) { int a = 10 , b = 4 ; bool res = ( ( a != b ) || printf ( " GeeksQuiz " ) ) ; return 0 ; }
How to swap two bits in a given integer ? | C program to swap bits in an integer ; This function swaps bit at positions p1 and p2 in an integer n ; Move p1 'th to rightmost side ; Move p2 'th to rightmost side ; XOR the two bits ; Put the xor bit back to their original positions ; XOR ' x ' with the original number so that the two sets are swapped ; Driver program to test above function
#include <stdio.h> NEW_LINE int swapBits ( unsigned int n , unsigned int p1 , unsigned int p2 ) { unsigned int bit1 = ( n >> p1 ) & 1 ; unsigned int bit2 = ( n >> p2 ) & 1 ; unsigned int x = ( bit1 ^ bit2 ) ; x = ( x << p1 ) | ( x << p2 ) ; unsigned int result = n ^ x ; } int main ( ) { int res = swapBits ( 28 , 0 , 3 ) ; printf ( " Result ▁ = ▁ % d ▁ " , res ) ; return 0 ; }
Write a function that returns 2 for input 1 and returns 1 for 2 |
int invert ( int x ) { if ( x == 1 ) return 2 ; else return 1 ; }
Write a function that returns 2 for input 1 and returns 1 for 2 |
int invertSub ( int x ) { return ( 3 - x ) ; }
Bitwise Operators in C / C ++ | ; Function to return the only odd occurring element ; Driver Method
#include <stdio.h> NEW_LINE int findOdd ( int arr [ ] , int n ) { int res = 0 , i ; for ( i = 0 ; i < n ; i ++ ) res ^= arr [ i ] ; return res ; } int main ( void ) { int arr [ ] = { 12 , 12 , 14 , 90 , 14 , 14 , 14 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printf ( " The ▁ odd ▁ occurring ▁ element ▁ is ▁ % d ▁ " , findOdd ( arr , n ) ) ; return 0 ; }
Bitwise Operators in C / C ++ |
#include <stdio.h> NEW_LINE int main ( ) { int x = 2 , y = 5 ; ( x & y ) ? printf ( " True ▁ " ) : printf ( " False ▁ " ) ; ( x && y ) ? printf ( " True ▁ " ) : printf ( " False ▁ " ) ; return 0 ; }
Hamming code Implementation in C / C ++ | C program for the above approach ; Store input bits ; Store hamming code ; Function to calculate bit for ith position ; Traverse to store Hamming Code ; If current boit is 1 ; Update i ; Function to calculate hamming code ; Find msg bits having set bit at x 'th position of number ; Traverse the msgBits ; Update the code ; Update the code [ i ] to the input character at index j ; Traverse and update the hamming code ; Find current position ; Find value at current position ; Update the code ; Print the Hamming Code ; Driver Code ; Given input message Bit ; Function Call
#include <math.h> NEW_LINE #include <stdio.h> NEW_LINE int input [ 32 ] ; int code [ 32 ] ; int ham_calc ( int , int ) ; void solve ( int input [ ] , int ) ; int ham_calc ( int position , int c_l ) { int count = 0 , i , j ; i = position - 1 ; while ( i < c_l ) { for ( j = i ; j < i + position ; j ++ ) { if ( code [ j ] == 1 ) count ++ ; } i = i + 2 * position ; } if ( count % 2 == 0 ) return 0 ; else return 1 ; } void solve ( int input [ ] , int n ) { int i , p_n = 0 , c_l , j , k ; i = 0 ; while ( n > ( int ) pow ( 2 , i ) - ( i + 1 ) ) { p_n ++ ; i ++ ; } c_l = p_n + n ; j = k = 0 ; for ( i = 0 ; i < c_l ; i ++ ) { if ( i == ( ( int ) pow ( 2 , k ) - 1 ) ) { code [ i ] = 0 ; k ++ ; } else { code [ i ] = input [ j ] ; j ++ ; } } for ( i = 0 ; i < p_n ; i ++ ) { int position = ( int ) pow ( 2 , i ) ; int value = ham_calc ( position , c_l ) ; code [ position - 1 ] = value ; } printf ( " The generated Code Word is : " for ( i = 0 ; i < c_l ; i ++ ) { printf ( " % d " , code [ i ] ) ; } } void main ( ) { input [ 0 ] = 0 ; input [ 1 ] = 1 ; input [ 2 ] = 1 ; input [ 3 ] = 1 ; int N = 4 ; solve ( input , N ) ; }
First non | CPP program to find first non - repeating character using 1D array and one traversal . ; The function returns index of the first non - repeating character in a string . If all characters are repeating then returns INT_MAX ; Initialize all characters as absent . ; After below loop , the value of arr [ x ] is going to be index of of x if x appears only once . Else the value is going to be either - 1 or - 2. ; If this character occurs only once and appears before the current result , then update the result ; Driver program to test above function
#include <limits.h> NEW_LINE #include <stdio.h> NEW_LINE #include <math.h> NEW_LINE #define NO_OF_CHARS 256 NEW_LINE int firstNonRepeating ( char * str ) { int arr [ NO_OF_CHARS ] ; for ( int i = 0 ; i < NO_OF_CHARS ; i ++ ) arr [ i ] = -1 ; for ( int i = 0 ; str [ i ] ; i ++ ) { if ( arr [ str [ i ] ] == -1 ) arr [ str [ i ] ] = i ; else arr [ str [ i ] ] = -2 ; } int res = INT_MAX ; for ( int i = 0 ; i < NO_OF_CHARS ; i ++ ) if ( arr [ i ] >= 0 ) res = min ( res , arr [ i ] ) ; return res ; } int main ( ) { char str [ ] = " geeksforgeeks " ; int index = firstNonRepeating ( str ) ; if ( index == INT_MAX ) printf ( " Either ▁ all ▁ characters ▁ are ▁ " " repeating ▁ or ▁ string ▁ is ▁ empty " ) ; else printf ( " First ▁ non - repeating ▁ character " " ▁ is ▁ % c " , str [ index ] ) ; return 0 ; }
Triacontagon Number | C program for above approach ; Finding the nth triacontagonal Number ; Driver program to test above function
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE int triacontagonalNum ( int n ) { return ( 28 * n * n - 26 * n ) / 2 ; } int main ( ) { int n = 3 ; printf ( "3rd ▁ triacontagonal ▁ Number ▁ is ▁ = ▁ % d " , triacontagonalNum ( n ) ) ; return 0 ; }
Hexacontagon Number | C program for above approach ; Finding the nth hexacontagon Number ; Driver program to test above function
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE int hexacontagonNum ( int n ) { return ( 58 * n * n - 56 * n ) / 2 ; } int main ( ) { int n = 3 ; printf ( "3rd ▁ hexacontagon ▁ Number ▁ is ▁ = ▁ % d " , hexacontagonNum ( n ) ) ; return 0 ; }
Enneacontagon Number | C program for above approach ; Finding the nth enneacontagon Number ; Driver program to test above function
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE int enneacontagonNum ( int n ) { return ( 88 * n * n - 86 * n ) / 2 ; } int main ( ) { int n = 3 ; printf ( "3rd ▁ enneacontagon ▁ Number ▁ is ▁ = ▁ % d " , enneacontagonNum ( n ) ) ; return 0 ; }
Triacontakaidigon Number | C program for above approach ; Finding the nth triacontakaidigon Number ; Driver program to test above function
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE int triacontakaidigonNum ( int n ) { return ( 30 * n * n - 28 * n ) / 2 ; } int main ( ) { int n = 3 ; printf ( "3rd ▁ triacontakaidigon ▁ Number ▁ is ▁ = ▁ % d " , triacontakaidigonNum ( n ) ) ; return 0 ; }
Icosihexagonal Number | C program for above approach ; Finding the nth Icosihexagonal Number ; Driver program to test above function
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE int IcosihexagonalNum ( int n ) { return ( 24 * n * n - 22 * n ) / 2 ; } int main ( ) { int n = 3 ; printf ( "3rd ▁ Icosihexagonal ▁ Number ▁ is ▁ = ▁ % d " , IcosihexagonalNum ( n ) ) ; return 0 ; }
Icosikaioctagon or Icosioctagon Number | C program for above approach ; Finding the nth icosikaioctagonal Number ; Driver program to test above function
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE int icosikaioctagonalNum ( int n ) { return ( 26 * n * n - 24 * n ) / 2 ; } int main ( ) { int n = 3 ; printf ( "3rd ▁ icosikaioctagonal ▁ Number ▁ is ▁ = ▁ % d " , icosikaioctagonalNum ( n ) ) ; return 0 ; }
Octacontagon Number | C program for above approach ; Finding the nth octacontagon Number ; Driver program to test above function
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE int octacontagonNum ( int n ) { return ( 78 * n * n - 76 * n ) / 2 ; } int main ( ) { int n = 3 ; printf ( "3rd ▁ octacontagon ▁ Number ▁ is ▁ = ▁ % d " , octacontagonNum ( n ) ) ; return 0 ; }
Hectagon Number | C program for above approach ; Finding the nth hectagon Number ; Driver program to test above function
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE int hectagonNum ( int n ) { return ( 98 * n * n - 96 * n ) / 2 ; } int main ( ) { int n = 3 ; printf ( "3rd ▁ hectagon ▁ Number ▁ is ▁ = ▁ % d " , hectagonNum ( n ) ) ; return 0 ; }
Tetracontagon Number | C program for above approach ; Finding the nth tetracontagon Number ; Driver program to test above function
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE int tetracontagonNum ( int n ) { return ( 38 * n * n - 36 * n ) / 2 ; } int main ( ) { int n = 3 ; printf ( "3rd ▁ tetracontagon ▁ Number ▁ is ▁ = ▁ % d " , tetracontagonNum ( n ) ) ; return 0 ; }
Search an element in a reverse sorted array | C program for the above approach ; Function to search if element X is present in reverse sorted array ; Store the first index of the subarray in which X lies ; Store the last index of the subarray in which X lies ; Store the middle index of the subarray ; Check if value at middle index of the subarray equal to X ; Element is found ; If X is smaller than the value at middle index of the subarray ; Search in right half of subarray ; Search in left half of subarray ; If X not found ; Driver Code
#include <stdio.h> NEW_LINE int binarySearch ( int arr [ ] , int N , int X ) { int start = 0 ; int end = N ; while ( start <= end ) { int mid = start + ( end - start ) / 2 ; if ( X == arr [ mid ] ) { return mid ; } else if ( X < arr [ mid ] ) { start = mid + 1 ; } else { end = mid - 1 ; } } return -1 ; } int main ( ) { int arr [ ] = { 5 , 4 , 3 , 2 , 1 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int X = 4 ; int res = binarySearch ( arr , N , X ) ; printf ( " ▁ % d ▁ " , res ) ; return 0 ; }
Pancake sorting | C program to sort array using pancake sort ; Reverses arr [ 0. . i ] ; Returns index of the maximum element in arr [ 0. . n - 1 ] ; The main function that sorts given array using flip operations ; Start from the complete array and one by one reduce current size by one ; Find index of the maximum element in arr [ 0. . curr_size - 1 ] ; Move the maximum element to end of current array if it 's not already at the end ; To move at the end , first move maximum number to beginning ; Now move the maximum number to end by reversing current array ; A utility function to print n array of size n ; Driver program to test above function
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE void flip ( int arr [ ] , int i ) { int temp , start = 0 ; while ( start < i ) { temp = arr [ start ] ; arr [ start ] = arr [ i ] ; arr [ i ] = temp ; start ++ ; i -- ; } } int findMax ( int arr [ ] , int n ) { int mi , i ; for ( mi = 0 , i = 0 ; i < n ; ++ i ) if ( arr [ i ] > arr [ mi ] ) mi = i ; return mi ; } void pancakeSort ( int * arr , int n ) { for ( int curr_size = n ; curr_size > 1 ; -- curr_size ) { int mi = findMax ( arr , curr_size ) ; if ( mi != curr_size - 1 ) { flip ( arr , mi ) ; flip ( arr , curr_size - 1 ) ; } } } void printArray ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; ++ i ) printf ( " % d ▁ " , arr [ i ] ) ; } int main ( ) { int arr [ ] = { 23 , 10 , 20 , 11 , 12 , 6 , 7 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; pancakeSort ( arr , n ) ; puts ( " Sorted ▁ Array ▁ " ) ; printArray ( arr , n ) ; return 0 ; }