text
stringlengths
17
4.49k
code
stringlengths
49
5.46k
Program to check if N is a Pentagonal Number | C ++ program to check pentagonal numbers . ; Function to determine if N is pentagonal or not . ; Substitute values of i in the formula . ; Driver Code
#include <iostream> NEW_LINE using namespace std ; bool isPentagonal ( int N ) { int i = 1 , M ; do { M = ( 3 * i * i - i ) / 2 ; i += 1 ; } while ( M < N ) ; return ( M == N ) ; } int main ( ) { int N = 12 ; if ( isPentagonal ( N ) ) cout << N << " ▁ is ▁ pentagonal ▁ " << endl ; else cout << N << " ▁ is ▁ not ▁ pentagonal " << endl ; return 0 ; }
Sum of fourth powers of the first n natural numbers | CPP Program to find the sum of forth powers of first n natural numbers ; Return the sum of forth power of first n natural numbers ; Driven Program
#include <bits/stdc++.h> NEW_LINE using namespace std ; long long int fourthPowerSum ( int n ) { long long int sum = 0 ; for ( int i = 1 ; i <= n ; i ++ ) sum = sum + ( i * i * i * i ) ; return sum ; } int main ( ) { int n = 6 ; cout << fourthPowerSum ( n ) << endl ; return 0 ; }
Sum of fourth powers of the first n natural numbers | CPP Program to find the sum of forth power of first n natural numbers ; Return the sum of forth power of first n natural numbers ; Driven Program
#include <bits/stdc++.h> NEW_LINE using namespace std ; long long int fourthPowerSum ( int n ) { return ( ( 6 * n * n * n * n * n ) + ( 15 * n * n * n * n ) + ( 10 * n * n * n ) - n ) / 30 ; } int main ( ) { int n = 6 ; cout << fourthPowerSum ( n ) << endl ; return 0 ; }
Find unit digit of x raised to power y | C ++ code to find the unit digit of x raised to power y . ; find unit digit ; Get last digit of x ; Last cyclic modular value ; here we simply return the unit digit or the power of a number ; Driver code ; get unit digit number here we pass the unit digit of x and the last cyclicity number that is y % 4
#include <iostream> NEW_LINE #include <math.h> NEW_LINE using namespace std ; int unitnumber ( int x , int y ) { x = x % 10 ; if ( y != 0 ) y = y % 4 + 4 ; return ( ( ( int ) ( pow ( x , y ) ) ) % 10 ) ; } int main ( ) { int x = 133 , y = 5 ; cout << unitnumber ( x , y ) ; return 0 ; }
Aliquot sum | CPP program for aliquot sum ; Function to calculate sum of all proper divisors ; Driver Code
#include <iostream> NEW_LINE using namespace std ; int aliquotSum ( int n ) { int sum = 0 ; for ( int i = 1 ; i < n ; i ++ ) if ( n % i == 0 ) sum += i ; return sum ; } int main ( ) { int n = 12 ; cout << aliquotSum ( n ) ; return 0 ; }
Average of Squares of Natural Numbers | C ++ program to get the Average of Square of first n natural numbers ; Function to get the average ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; float AvgofSquareN ( int n ) { return ( float ) ( ( n + 1 ) * ( 2 * n + 1 ) ) / 6 ; } int main ( ) { int n = 10 ; cout << AvgofSquareN ( n ) ; return 0 ; }
Program to implement Simpson 's 3/8 rule | CPP program to implement Simpson 's rule ; Given function to be integrated ; Function to perform calculations ; Calculates value till integral limit ; Driver Code
#include <iostream> NEW_LINE using namespace std ; float func ( float x ) { return ( 1 / ( 1 + x * x ) ) ; } float calculate ( float lower_limit , float upper_limit , int interval_limit ) { float value ; float interval_size = ( upper_limit - lower_limit ) / interval_limit ; float sum = func ( lower_limit ) + func ( upper_limit ) ; for ( int i = 1 ; i < interval_limit ; i ++ ) { if ( i % 3 == 0 ) sum = sum + 2 * func ( lower_limit + i * interval_size ) ; else sum = sum + 3 * func ( lower_limit + i * interval_size ) ; } return ( 3 * interval_size / 8 ) * sum ; } int main ( ) { int interval_limit = 10 ; float lower_limit = 1 ; float upper_limit = 10 ; float integral_res = calculate ( lower_limit , upper_limit , interval_limit ) ; cout << integral_res ; return 0 ; }
Container with Most Water | C ++ code for Max Water Container ; Calculating the max area ; Driver code
#include <iostream> NEW_LINE using namespace std ; int maxArea ( int A [ ] , int len ) { int area = 0 ; for ( int i = 0 ; i < len ; i ++ ) { for ( int j = i + 1 ; j < len ; j ++ ) { area = max ( area , min ( A [ j ] , A [ i ] ) * ( j - i ) ) ; } } return area ; } int main ( ) { int a [ ] = { 1 , 5 , 4 , 3 } ; int b [ ] = { 3 , 1 , 2 , 4 , 5 } ; int len1 = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << maxArea ( a , len1 ) ; int len2 = sizeof ( b ) / sizeof ( b [ 0 ] ) ; cout << endl << maxArea ( b , len2 ) ; }
Program for focal length of a lens | C ++ program to determine the focal length of a lens ; Function to determine the focal length of a lens ; Driver function ; variable to store the distance between the lens and the image ; variable to store the distance between the lens and the object
#include <iostream> NEW_LINE using namespace std ; float focal_length ( float image_distance , float object_distance ) { return 1 / ( ( 1 / image_distance ) + ( 1 / object_distance ) ) ; } int main ( ) { float image_distance = 2 ; float object_distance = 50 ; cout << " Focal ▁ length ▁ of ▁ a ▁ lens ▁ is ▁ " << focal_length ( image_distance , object_distance ) << " ▁ units ▁ . " ; return 0 ; }
Count numbers in range L | C ++ program to Count numbers in range L - R that are divisible by all of its non - zero digits ; check if the number is divisible by the digits . ; function to calculate the number of numbers ; Driver function
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool check ( int n ) { int m = n ; while ( n ) { int r = n % 10 ; if ( r > 0 ) if ( ( m % r ) != 0 ) return false ; n /= 10 ; } return true ; } int count ( int l , int r ) { int ans = 0 ; for ( int i = l ; i <= r ; i ++ ) if ( check ( i ) ) ans += 1 ; return ans ; } int main ( ) { int l = 10 , r = 20 ; cout << count ( l , r ) ; return 0 ; }
Sum of the Series 1 / ( 1 * 2 ) + 1 / ( 2 * 3 ) + 1 / ( 3 * 4 ) + 1 / ( 4 * 5 ) + . . . . . | C ++ program to find the sum of given series ; function to find the sum of given series ; Computing sum term by term ; driver program to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; double sumOfTheSeries ( int n ) { double sum = 0.0 ; for ( int i = 1 ; i <= n ; i ++ ) sum += 1.0 / ( i * ( i + 1 ) ) ; return sum ; } int main ( ) { int n = 10 ; cout << sumOfTheSeries ( n ) ; return 0 ; }
Sum of series ( n / 1 ) + ( n / 2 ) + ( n / 3 ) + ( n / 4 ) + ... ... . + ( n / n ) | CPP program to find sum of given series ; function to find sum of series ; driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; long long int sum ( long long int n ) { long long int root = sqrt ( n ) ; long long int ans = 0 ; for ( int i = 1 ; i <= root ; i ++ ) ans += n / i ; ans = 2 * ans - ( root * root ) ; return ans ; } int main ( ) { long long int n = 35 ; cout << sum ( n ) ; return 0 ; }
Sum of the series 2 + ( 2 + 4 ) + ( 2 + 4 + 6 ) + ( 2 + 4 + 6 + 8 ) + Γ’ €¦ Γ’ €¦ + ( 2 + 4 + 6 + 8 + Γ’ €¦ . + 2 n ) | C ++ implementation to find the sum of the given series ; function to find the sum of the given series ; sum of 1 st n natural numbers ; sum of squares of 1 st n natural numbers ; required sum ; Driver program to test above
#include <bits/stdc++.h> NEW_LINE using namespace std ; int sumOfTheSeries ( int n ) { int sum_n = ( n * ( n + 1 ) / 2 ) ; int sum_sq_n = ( n * ( n + 1 ) / 2 ) * ( 2 * n + 1 ) / 3 ; return ( sum_n + sum_sq_n ) ; } int main ( ) { int n = 5 ; cout << " Sum ▁ = ▁ " << sumOfTheSeries ( n ) ; return 0 ; }
Sum of squares of binomial coefficients | CPP Program to find the sum of square of binomial coefficient . ; Return the sum of square of binomial coefficient ; Calculate value of Binomial Coefficient in bottom up manner ; Base Cases ; Calculate value using previously stored values ; Finding the sum of square of binomial coefficient . ; Driven Program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int sumofsquare ( int n ) { int C [ n + 1 ] [ n + 1 ] ; int i , j ; for ( i = 0 ; i <= n ; i ++ ) { for ( j = 0 ; j <= min ( i , n ) ; j ++ ) { if ( j == 0 j == i ) C [ i ] [ j ] = 1 ; else C [ i ] [ j ] = C [ i - 1 ] [ j - 1 ] + C [ i - 1 ] [ j ] ; } } int sum = 0 ; for ( int i = 0 ; i <= n ; i ++ ) sum += ( C [ n ] [ i ] * C [ n ] [ i ] ) ; return sum ; } int main ( ) { int n = 4 ; cout << sumofsquare ( n ) << endl ; return 0 ; }
Program to find sum of series 1 + 2 + 2 + 3 + 3 + 3 + . . . + n | Program to find sum of series 1 + 2 + 2 + 3 + . . . + n ; Function that find sum of series . ; Driver function ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int sumOfSeries ( int n ) { int sum = 0 ; for ( int i = 1 ; i <= n ; i ++ ) for ( int j = 1 ; j <= i ; j ++ ) sum = sum + i ; return sum ; } int main ( ) { int n = 10 ; cout << sumOfSeries ( n ) ; return 0 ; }
Find sum of even index binomial coefficients | CPP Program to find sum of even index term ; Return the sum of even index term ; Calculate value of Binomial Coefficient in bottom up manner ; Base Cases ; Calculate value using previously stored values ; finding sum of even index term . ; Driver Program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int evenSum ( int n ) { int C [ n + 1 ] [ n + 1 ] ; int i , j ; for ( i = 0 ; i <= n ; i ++ ) { for ( j = 0 ; j <= min ( i , n ) ; j ++ ) { if ( j == 0 j == i ) C [ i ] [ j ] = 1 ; else C [ i ] [ j ] = C [ i - 1 ] [ j - 1 ] + C [ i - 1 ] [ j ] ; } } int sum = 0 ; for ( int i = 0 ; i <= n ; i += 2 ) sum += C [ n ] [ i ] ; return sum ; } int main ( ) { int n = 4 ; cout << evenSum ( n ) << endl ; return 0 ; }
Check if a number can be written as sum of three consecutive integers | CPP Program to check if a number can be written as sum of three consecutive integer . ; function to check if a number can be written as sum of three consecutive integers . ; if n is multiple of 3 ; else print " - 1" . ; Driver Program
#include <bits/stdc++.h> NEW_LINE using namespace std ; void checksum ( int n ) { if ( n % 3 == 0 ) cout << n / 3 - 1 << " ▁ " << n / 3 << " ▁ " << n / 3 + 1 ; else cout << " - 1" ; } int main ( ) { int n = 6 ; checksum ( n ) ; return 0 ; }
Sum of all divisors from 1 to n | C ++ program to find sum of all divisor of number up to ' n ' ; Utility function to find sum of all divisor of number up to ' n ' ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int divisorSum ( int n ) { int sum = 0 ; for ( int i = 1 ; i <= n ; ++ i ) sum += ( n / i ) * i ; return sum ; } int main ( ) { int n = 4 ; cout << " ▁ " << divisorSum ( n ) << endl ; n = 5 ; cout << " ▁ " << divisorSum ( n ) << endl ; return 0 ; }
Sum of all divisors from 1 to n | ; long long t1 = i * ( num / i - i + 1 ) ; adding i every time it appears with numbers greater than or equal to itself long long t2 = ( ( ( num / i ) * ( num / i + 1 ) ) / 2 ) - ( ( i * ( i + 1 ) ) / 2 ) ; adding numbers that appear with i and are greater than i ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; long long sum_all_divisors ( long long num ) { long long sum = 0 ; for ( long long i = 1 ; i <= sqrt ( num ) ; i ++ ) { sum += t1 + t2 ; } return sum ; } int main ( ) { int n ; long long sum = sum_all_divisors ( n ) ; cout << sum << ' ' ; return 0 ; }
N | CPP program to find Nth polite number ; function to evaluate Nth polite number ; driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; double polite ( double n ) { n += 1 ; double base = 2 ; return n + ( log ( ( n + ( log ( n ) / log ( base ) ) ) ) ) / log ( base ) ; } int main ( ) { double n = 7 ; cout << ( int ) polite ( n ) ; return 0 ; }
Find the number of stair steps | C ++ program to find the number of steps ; Modified Binary search function to solve the equation ; if mid is solution to equation ; if our solution to equation lies between mid and mid - 1 ; if solution to equation is greater than mid ; if solution to equation is less than mid ; driver function ; call binary search method to solve for limits 1 to T ; Because our pattern starts from 2 , 3 , 4 , 5. . . so , we subtract 1 from ans
#include <bits/stdc++.h> NEW_LINE using namespace std ; int solve ( int low , int high , int T ) { while ( low <= high ) { int mid = ( low + high ) / 2 ; if ( ( mid * ( mid + 1 ) ) == T ) return mid ; if ( mid > 0 && ( mid * ( mid + 1 ) ) > T && ( mid * ( mid - 1 ) ) <= T ) return mid - 1 ; if ( ( mid * ( mid + 1 ) ) > T ) high = mid - 1 ; else low = mid + 1 ; } return -1 ; } int main ( ) { int T = 15 ; int ans = solve ( 1 , T , 2 * T ) ; if ( ans != -1 ) ans -- ; cout << " Number ▁ of ▁ stair ▁ steps ▁ = ▁ " << ans << endl ; return 0 ; }
Check for integer overflow on multiplication | CPP program to check for integer overflow on multiplication ; Function to check whether there is overflow in a * b or not . It returns true if there is overflow . ; Check if either of them is zero ; Driver code
#include <iostream> NEW_LINE using namespace std ; bool isOverflow ( long long a , long long b ) { if ( a == 0 b == 0 ) return false ; long long result = a * b ; if ( a == result / b ) return false ; else return true ; } int main ( ) { long long a = 10000000000 , b = -10000000000 ; if ( isOverflow ( a , b ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Sum of first n odd numbers in O ( 1 ) Complexity | A naive CPP program to find sum of first n odd numbers ; Returns the sum of first n odd numbers ; Driver function
#include <iostream> NEW_LINE using namespace std ; int oddSum ( int n ) { int sum = 0 , curr = 1 ; for ( int i = 0 ; i < n ; i ++ ) { sum += curr ; curr += 2 ; } return sum ; } int main ( ) { int n = 20 ; cout << " ▁ Sum ▁ of ▁ first ▁ " << n << " ▁ Odd ▁ Numbers ▁ is : ▁ " << oddSum ( n ) ; return 0 ; }
Sum of first n odd numbers in O ( 1 ) Complexity | Efficient program to find sum of first n odd numbers ; Returns the sum of first n odd numbers ; Driver function
#include <iostream> NEW_LINE using namespace std ; int oddSum ( int n ) { return ( n * n ) ; } int main ( ) { int n = 20 ; cout << " ▁ Sum ▁ of ▁ first ▁ " << n << " ▁ Odd ▁ Numbers ▁ is : ▁ " << oddSum ( n ) ; return 0 ; }
K | CPP program to count all those numbers in given range whose count of prime factors is k ; Returns the sum of first n odd numbers ; Count prime factors of all numbers till B . ; Print all numbers with k prime factors ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printKPFNums ( int A , int B , int K ) { bool prime [ B + 1 ] = { true } ; int p_factors [ B + 1 ] = { 0 } ; for ( int p = 2 ; p <= B ; p ++ ) if ( p_factors [ p ] == 0 ) for ( int i = p ; i <= B ; i += p ) p_factors [ i ] ++ ; for ( int i = A ; i <= B ; i ++ ) if ( p_factors [ i ] == K ) cout << i << " ▁ " ; } int main ( ) { int A = 14 , B = 18 , K = 2 ; printKPFNums ( A , B , K ) ; return 0 ; }
Queries for maximum difference between prime numbers in given ranges | CPP program to find maximum differences between two prime numbers in given ranges ; Precompute Sieve , Prefix array , Suffix array ; Sieve of Eratosthenes ; Precomputing Prefix array . ; Precompute Suffix array . ; Function to solve each query ; Driven Program
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 100005 NEW_LINE bool prime [ MAX ] ; int prefix [ MAX ] , suffix [ MAX ] ; void precompute ( int prefix [ ] , int suffix [ ] ) { memset ( prime , true , sizeof ( prime ) ) ; for ( int i = 2 ; i * i < MAX ; i ++ ) { if ( prime [ i ] ) { for ( int j = i * i ; j < MAX ; j += i ) prime [ j ] = false ; } } prefix [ 1 ] = 1 ; suffix [ MAX - 1 ] = 1e9 + 7 ; for ( int i = 2 ; i < MAX ; i ++ ) { if ( prime [ i ] ) prefix [ i ] = i ; else prefix [ i ] = prefix [ i - 1 ] ; } for ( int i = MAX - 1 ; i > 1 ; i -- ) { if ( prime [ i ] ) suffix [ i ] = i ; else suffix [ i ] = suffix [ i + 1 ] ; } } int query ( int prefix [ ] , int suffix [ ] , int L , int R ) { if ( prefix [ R ] < L suffix [ L ] > R ) return 0 ; else return prefix [ R ] - suffix [ L ] ; } int main ( ) { int q = 3 ; int L [ ] = { 2 , 2 , 24 } ; int R [ ] = { 5 , 2 , 28 } ; precompute ( prefix , suffix ) ; for ( int i = 0 ; i < q ; i ++ ) cout << query ( prefix , suffix , L [ i ] , R [ i ] ) << endl ; return 0 ; }
Sum of the Series 1 + x / 1 + x ^ 2 / 2 + x ^ 3 / 3 + . . + x ^ n / n | C ++ program to find sum of series 1 + x / 1 + x ^ 2 / 2 + x ^ 3 / 3 + ... . + x ^ n / n ; Funciton to print the sum of the series ; Driver code
#include <math.h> NEW_LINE #include <iostream> NEW_LINE #include <boost/format.hpp> NEW_LINE class gfg { public : double sum ( int x , int n ) { double i , total = 1.0 ; for ( i = 1 ; i <= n ; i ++ ) total = total + ( pow ( x , i ) / i ) ; return total ; } } ; int main ( ) { gfg g ; int x = 2 ; int n = 5 ; std :: cout << boost :: format ( " % .2f " ) % g . sum ( x , n ) ; return 0 ; }
Find if a number is part of AP whose first element and difference are given | C ++ program to check if x exist or not in the given AP . ; returns yes if exist else no . ; If difference is 0 , then x must be same as a . ; Else difference between x and a must be divisible by d . ; Driver code .
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isMember ( int a , int d , int x ) { if ( d == 0 ) return ( x == a ) ; return ( ( x - a ) % d == 0 && ( x - a ) / d >= 0 ) ; } int main ( ) { int a = 1 , x = 7 , d = 3 ; if ( isMember ( a , d , x ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Number of GP ( Geometric Progression ) subsequences of size 3 | C ++ program to count GP subsequences of size 3. ; to calculate nCr DP approach ; nC0 is 1 ; Compute next row of pascal triangle using the previous row ; Returns count of G . P . subsequences with length 3 and common ratio r ; hashing to maintain left and right array elements to the main count ; stores the answer ; traverse through the elements ; IF RATIO IS ONE ; traverse the count in hash ; calculating nC3 , where ' n ' is the number of times each number is repeated in the input ; traverse through all elements and find out the number of elements as k1 * k2 ; keep the count of left and right elements left is a [ i ] / r and right a [ i ] * r ; if the current element is divisible by k , count elements in left hash . ; decrease the count in right hash ; number of right elements ; calculate the answer ; left count of a [ i ] ; returns answer ; driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int binomialCoeff ( int n , int k ) { int C [ k + 1 ] ; memset ( C , 0 , sizeof ( C ) ) ; C [ 0 ] = 1 ; for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = min ( i , k ) ; j > 0 ; j -- ) C [ j ] = C [ j ] + C [ j - 1 ] ; } return C [ k ] ; } long long subsequences ( int a [ ] , int n , int r ) { unordered_map < int , int > left , right ; long long ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) right [ a [ i ] ] ++ ; if ( r == 1 ) { for ( auto i : right ) { ans += binomialCoeff ( i . second , 3 ) ; } return ans ; } for ( int i = 0 ; i < n ; i ++ ) { long long c1 = 0 , c2 = 0 ; if ( a [ i ] % r == 0 ) c1 = left [ a [ i ] / r ] ; right [ a [ i ] ] -- ; c2 = right [ a [ i ] * r ] ; ans += c1 * c2 ; left [ a [ i ] ] ++ ; } return ans ; } int main ( ) { int a [ ] = { 1 , 2 , 6 , 2 , 3 , 6 , 9 , 18 , 3 , 9 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; int r = 3 ; cout << subsequences ( a , n , r ) ; return 0 ; }
Check whether a number can be represented by sum of two squares | A brute force approach based implementation to find if a number can be written as sum of two squares . ; function to check if there exist two numbers sum of whose squares is n . ; driver Program
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool sumSquare ( int n ) { for ( long i = 1 ; i * i <= n ; i ++ ) for ( long j = 1 ; j * j <= n ; j ++ ) if ( i * i + j * j == n ) { cout << i << " ^ 2 ▁ + ▁ " << j << " ^ 2" << endl ; return true ; } return false ; } int main ( ) { int n = 25 ; if ( sumSquare ( n ) ) cout << " Yes " ; else cout << " No " ; }
Queries to count minimum flips required to fill a binary submatrix with 0 s only | C ++ program for the above approach ; Function to compute the matrix prefixCnt [ M ] [ N ] from mat [ M ] [ N ] such that prefixCnt [ i ] [ j ] stores the count of 0 's from (0, 0) to (i, j) ; Initialize prefixCnt [ i ] [ j ] with 1 if mat [ i ] [ j ] is 0 ; Otherwise , assign with 0 ; Calculate prefix sum for each row ; Calculate prefix sum for each column ; Function to compute count of 0 's in submatrix from (pi, pj) to (qi, qj) from prefixCnt[M][N] ; Initialize that count of 0 's in the sub-matrix within indices (0, 0) to (qi, qj) ; Subtract count of 0 's within indices (0, 0) and (pi-1, qj) ; Subtract count of 0 's within indices (0, 0) and (qi, pj-1) ; Add prefixCnt [ pi - 1 ] [ pj - 1 ] because its value has been added once but subtracted twice ; Function to count the 0 s in the each given submatrix ; Stores the prefix sum of each row and column ; Compute matrix prefixCnt [ ] [ ] ; Function Call for each query ; Driver Code ; Given matrix ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define M 6 NEW_LINE #define N 7 NEW_LINE void preCompute ( int mat [ M ] [ N ] , int prefixCnt [ M ] [ N ] ) { for ( int i = 0 ; i < M ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) { if ( mat [ i ] [ j ] == 0 ) { prefixCnt [ i ] [ j ] = 1 ; } else { prefixCnt [ i ] [ j ] = 0 ; } } } for ( int i = 0 ; i < M ; i ++ ) for ( int j = 1 ; j < N ; j ++ ) prefixCnt [ i ] [ j ] += prefixCnt [ i ] [ j - 1 ] ; for ( int i = 1 ; i < M ; i ++ ) for ( int j = 0 ; j < N ; j ++ ) prefixCnt [ i ] [ j ] += prefixCnt [ i - 1 ] [ j ] ; } int countQuery ( int prefixCnt [ M ] [ N ] , int pi , int pj , int qi , int qj ) { int cnt = prefixCnt [ qi ] [ qj ] ; if ( pi > 0 ) cnt -= prefixCnt [ pi - 1 ] [ qj ] ; if ( pj > 0 ) cnt -= prefixCnt [ qi ] [ pj - 1 ] ; if ( pi > 0 && pj > 0 ) cnt += prefixCnt [ pi - 1 ] [ pj - 1 ] ; return cnt ; } void count0s ( int mat [ M ] [ N ] , int Q [ ] [ 4 ] , int sizeQ ) { int prefixCnt [ M ] [ N ] ; preCompute ( mat , prefixCnt ) ; for ( int i = 0 ; i < sizeQ ; i ++ ) { cout << countQuery ( prefixCnt , Q [ i ] [ 0 ] , Q [ i ] [ 1 ] , Q [ i ] [ 2 ] , Q [ i ] [ 3 ] ) << ' ▁ ' ; } } int main ( ) { int mat [ M ] [ N ] = { { 0 , 1 , 0 , 1 , 1 , 1 , 0 } , { 1 , 0 , 1 , 1 , 1 , 0 , 1 } , { 1 , 1 , 0 , 0 , 1 , 1 , 0 } , { 1 , 1 , 1 , 1 , 1 , 0 , 1 } , { 0 , 0 , 1 , 0 , 1 , 1 , 1 } , { 1 , 1 , 0 , 1 , 1 , 0 , 1 } } ; int Q [ ] [ 4 ] = { { 0 , 1 , 3 , 2 } , { 2 , 2 , 4 , 5 } , { 4 , 3 , 5 , 6 } } ; int sizeQ = sizeof ( Q ) / sizeof ( Q [ 0 ] ) ; count0s ( mat , Q , sizeQ ) ; return 0 ; }
Smallest root of the equation x ^ 2 + s ( x ) * x | CPP program to find smallest value of root of an equation under given constraints . ; function to check if the sum of digits is equal to the summation assumed ; calculate the sum of digit ; function to find the largest root possible . ; iterate for all possible sum of digits . ; check if discriminent is a perfect square . ; check if discriminent is a perfect square and if it as perefect root of the equation ; function returns answer ; driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool check ( long long a , long long b ) { long long int c = 0 ; while ( a != 0 ) { c = c + a % 10 ; a = a / 10 ; } return ( c == b ) ; } long long root ( long long n ) { bool found = 0 ; long long mx = 1e18 ; for ( long long i = 0 ; i <= 90 ; i ++ ) { long long s = i * i + 4 * n ; long long sq = sqrt ( s ) ; if ( sq * sq == s && check ( ( sq - i ) / 2 , i ) ) { found = 1 ; mx = min ( mx , ( sq - i ) / 2 ) ; } } if ( found ) return mx ; else return -1 ; } int main ( ) { long long n = 110 ; cout << root ( n ) ; }
Sum of digits of a given number to a given power | CPP program to illustrate the given problem ; Function to calculate sum ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int calculate ( int n , int power ) { int sum = 0 ; int bp = ( int ) pow ( n , power ) ; while ( bp != 0 ) { int d = bp % 10 ; sum += d ; bp /= 10 ; } return sum ; } int main ( ) { int n = 5 ; int power = 4 ; cout << calculate ( n , power ) ; }
Co | CPP program to represent a number as sum of a co - prime pair such that difference between them is minimum ; function to check if pair is co - prime or not ; function to find and print co - prime pair ; driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool coprime ( int a , int b ) { return ( __gcd ( a , b ) == 1 ) ; } void pairSum ( int n ) { int mid = n / 2 ; for ( int i = mid ; i >= 1 ; i -- ) { if ( coprime ( i , n - i ) == 1 ) { cout << i << " ▁ " << n - i ; break ; } } } int main ( ) { int n = 11 ; pairSum ( n ) ; return 0 ; }
Program for quotient and remainder of big number | CPP program to find quotient and remainder when a number is divided by large number represented as string . ; Function to calculate the modulus ; Store the modulus of big number ; Do step by step division ; Update modulo by concatenating current digit . ; Update quotient ; Update mod for next iteration . ; Flag used to remove starting zeros ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; typedef long long ll ; void modBigNumber ( string num , ll m ) { vector < int > vec ; ll mod = 0 ; for ( int i = 0 ; i < num . size ( ) ; i ++ ) { int digit = num [ i ] - '0' ; mod = mod * 10 + digit ; int quo = mod / m ; vec . push_back ( quo ) ; mod = mod % m ; } cout << " Remainder : " ▁ < < ▁ mod ▁ < < ▁ " " cout << " Quotient ▁ : ▁ " ; bool zeroflag = 0 ; for ( int i = 0 ; i < vec . size ( ) ; i ++ ) { if ( vec [ i ] == 0 && zeroflag == 0 ) continue ; zeroflag = 1 ; cout << vec [ i ] ; } return ; } int main ( ) { string num = "14598499948265358486" ; ll m = 487 ; modBigNumber ( num , m ) ; return 0 ; }
Queries to find whether a number has exactly four distinct factors or not | C ++ program to check whether number has exactly four distinct factors or not ; Initialize global variable according to given condition so that it can be accessible to all function ; Function to calculate all number having four distinct distinct factors ; Create a boolean array " prime [ 0 . . n ] " and initialize all entries it as true . A value in prime [ i ] will finally be false if i is not a prime , else true . ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; Initialize prime [ ] array which will contains all the primes from 1 - N ; Iterate over all the prime numbers ; Mark cube root of prime numbers ; Mark product of prime numbers ; Driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int N = 1e6 ; bool fourDiv [ N + 1 ] ; memset ( fourDiv , false , sizeof ( fourDiv ) ) ; void fourDistinctFactors ( ) { bool primeAll [ N + 1 ] ; memset ( primeAll , true , sizeof ( primeAll ) ) ; for ( int p = 2 ; p * p <= N ; p ++ ) { if ( primeAll [ p ] == true ) { for ( int i = p * 2 ; i <= N ; i += p ) primeAll [ i ] = false ; } } vector < int > prime ; for ( int p = 2 ; p <= N ; p ++ ) if ( primeAll [ p ] ) prime . push_back ( p ) ; for ( int i = 0 ; i < prime . size ( ) ; ++ i ) { int p = prime [ i ] ; if ( 1LL * p * p * p <= N ) fourDiv [ p * p * p ] = true ; for ( int j = i + 1 ; j < prime . size ( ) ; ++ j ) { int q = prime [ j ] ; if ( 1LL * p * q > N ) break ; fourDiv [ p * q ] = true ; } } } int main ( ) { fourDistinctFactors ( ) ; int num = 10 ; if ( fourDiv [ num ] ) cout << " Yes STRNEWLINE " ; else cout << " No STRNEWLINE " ; num = 12 ; if ( fourDiv [ num ] ) cout << " Yes STRNEWLINE " ; else cout << " No STRNEWLINE " ; return 0 ; }
Leonardo Number | A simple recursive program to find n - th leonardo number . ; Driver code
#include <iostream> NEW_LINE using namespace std ; int leonardo ( int n ) { int dp [ n + 1 ] ; dp [ 0 ] = dp [ 1 ] = 1 ; for ( int i = 2 ; i <= n ; i ++ ) dp [ i ] = dp [ i - 1 ] + dp [ i - 2 ] + 1 ; return dp [ n ] ; } int main ( ) { cout << leonardo ( 3 ) ; return 0 ; }
Cholesky Decomposition : Matrix Decomposition | CPP program to decompose a matrix using Cholesky Decomposition ; Decomposing a matrix into Lower Triangular ; if ( j == i ) summation for diagonals ; Evaluating L ( i , j ) using L ( j , j ) ; Displaying Lower Triangular and its Transpose ; Lower Triangular ; Transpose of Lower Triangular ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 100 ; void Cholesky_Decomposition ( int matrix [ ] [ MAX ] , int n ) { int lower [ n ] [ n ] ; memset ( lower , 0 , sizeof ( lower ) ) ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j <= i ; j ++ ) { int sum = 0 ; { for ( int k = 0 ; k < j ; k ++ ) sum += pow ( lower [ j ] [ k ] , 2 ) ; lower [ j ] [ j ] = sqrt ( matrix [ j ] [ j ] - sum ) ; } else { for ( int k = 0 ; k < j ; k ++ ) sum += ( lower [ i ] [ k ] * lower [ j ] [ k ] ) ; lower [ i ] [ j ] = ( matrix [ i ] [ j ] - sum ) / lower [ j ] [ j ] ; } } } cout << setw ( 6 ) << " ▁ Lower ▁ Triangular " << setw ( 30 ) << " Transpose " << endl ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) cout << setw ( 6 ) << lower [ i ] [ j ] << " TABSYMBOL " ; cout << " TABSYMBOL " ; for ( int j = 0 ; j < n ; j ++ ) cout << setw ( 6 ) << lower [ j ] [ i ] << " TABSYMBOL " ; cout << endl ; } } int main ( ) { int n = 3 ; int matrix [ ] [ MAX ] = { { 4 , 12 , -16 } , { 12 , 37 , -43 } , { -16 , -43 , 98 } } ; Cholesky_Decomposition ( matrix , n ) ; return 0 ; }
Program for sum of arithmetic series | Efficient solution to find sum of arithmetic series . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; float sumOfAP ( float a , float d , float n ) { float sum = ( n / 2 ) * ( 2 * a + ( n - 1 ) * d ) ; return sum ; } int main ( ) { float n = 20 ; float a = 2.5 , d = 1.5 ; cout << sumOfAP ( a , d , n ) ; return 0 ; }
Program for cube sum of first n natural numbers | Efficient CPP program to find sum of cubes of first n natural numbers that avoids overflow if result is going to be withing limits . ; Returns sum of first n natural numbers ; Driver code
#include <iostream> NEW_LINE using namespace std ; int sumOfSeries ( int n ) { int x ; if ( n % 2 == 0 ) x = ( n / 2 ) * ( n + 1 ) ; else x = ( ( n + 1 ) / 2 ) * n ; return x * x ; } int main ( ) { int n = 5 ; cout << sumOfSeries ( n ) ; return 0 ; }
Maximum value of | arr [ i ] | ; Return maximum value of | arr [ i ] - arr [ j ] | + | i - j | ; Iterating two for loop , one for i and another for j . ; Evaluating | arr [ i ] - arr [ j ] | + | i - j | and compare with previous maximum . ; Driven Program
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 10 NEW_LINE int findValue ( int arr [ ] , int n ) { int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = 0 ; j < n ; j ++ ) ans = max ( ans , abs ( arr [ i ] - arr [ j ] ) + abs ( i - j ) ) ; return ans ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findValue ( arr , n ) << endl ; return 0 ; }
Maximum value of | arr [ i ] | Efficient CPP program to find maximum value of | arr [ i ] - arr [ j ] | + | i - j | ; Return maximum | arr [ i ] - arr [ j ] | + | i - j | ; Calculating first_array and second_array ; Finding maximum and minimum value in first_array ; Storing the difference between maximum and minimum value in first_array ; Finding maximum and minimum value in second_array ; Storing the difference between maximum and minimum value in second_array ; Driven Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findValue ( int arr [ ] , int n ) { int a [ n ] , b [ n ] , tmp ; for ( int i = 0 ; i < n ; i ++ ) { a [ i ] = ( arr [ i ] + i ) ; b [ i ] = ( arr [ i ] - i ) ; } int x = a [ 0 ] , y = a [ 0 ] ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] > x ) x = a [ i ] ; if ( a [ i ] < y ) y = a [ i ] ; } int ans1 = ( x - y ) ; x = b [ 0 ] ; y = b [ 0 ] ; for ( int i = 0 ; i < n ; i ++ ) { if ( b [ i ] > x ) x = b [ i ] ; if ( b [ i ] < y ) y = b [ i ] ; } int ans2 = ( x - y ) ; return max ( ans1 , ans2 ) ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findValue ( arr , n ) << endl ; return 0 ; }
Number of subarrays having product less than K | CPP program to count subarrays having product less than k . ; Counter for single element ; Multiple subarray ; If this multiple is less than k , then increment ; Driver Code
#include <iostream> NEW_LINE using namespace std ; int countsubarray ( int array [ ] , int n , int k ) { int count = 0 ; int i , j , mul ; for ( i = 0 ; i < n ; i ++ ) { if ( array [ i ] < k ) count ++ ; mul = array [ i ] ; for ( j = i + 1 ; j < n ; j ++ ) { mul = mul * array [ j ] ; if ( mul < k ) count ++ ; else break ; } } return count ; } int main ( ) { int array [ ] = { 1 , 2 , 3 , 4 } ; int k = 10 ; int size = sizeof ( array ) / sizeof ( array [ 0 ] ) ; int count = countsubarray ( array , size , k ) ; cout << count << " STRNEWLINE " ; }
Perfect Cube factors of a Number | C ++ program for the above approach ; Function that returns the count of factors that are perfect cube ; To store the count of number of times a prime number divides N . ; To store the number of factors that are perfect cube ; Count number of 2 's that divides N ; Calculate ans according to above formula ; Check for all the possible numbers that can divide it ; Loop to check the number of times prime number i divides it ; Calculate ans according to above formula ; Return final count ; Driver Code ; Given number ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int noOfFactors ( int N ) { if ( N == 1 ) return 1 ; int count = 0 ; int ans = 1 ; while ( N % 2 == 0 ) { count ++ ; N = N / 2 ; } ans *= ( count / 3 + 1 ) ; for ( int i = 3 ; i * i <= N ; i = i + 2 ) { count = 0 ; while ( N % i == 0 ) { count ++ ; N = N / i ; } ans *= ( count / 3 + 1 ) ; } return ans ; } int main ( ) { int N = 216 ; cout << noOfFactors ( N ) ; return 0 ; }
Efficient program to print the number of factors of n numbers | C ++ program to count number of factors of an array of integers ; function to generate all prime factors of numbers from 1 to 10 ^ 6 ; Initializes all the positions with their value . ; Initializes all multiples of 2 with 2 ; A modified version of Sieve of Eratosthenes to store the smallest prime factor that divides every number . ; check if it has no prime factor . ; Initializes of j starting from i * i ; if it has no prime factor before , then stores the smallest prime divisor ; function to calculate number of factors ; stores the smallest prime number that divides n ; stores the count of number of times a prime number divides n . ; reduces to the next number after prime factorization of n ; false when prime factorization is done ; if the same prime number is dividing n , then we increase the count ; if its a new prime factor that is factorizing n , then we again set c = 1 and change dup to the new prime factor , and apply the formula explained above . ; prime factorizes a number ; for the last prime factor ; Driver program to test above function ; generate prime factors of number upto 10 ^ 6
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 1000001 ; int factor [ MAX ] = { 0 } ; void generatePrimeFactors ( ) { factor [ 1 ] = 1 ; for ( int i = 2 ; i < MAX ; i ++ ) factor [ i ] = i ; for ( int i = 4 ; i < MAX ; i += 2 ) factor [ i ] = 2 ; for ( int i = 3 ; i * i < MAX ; i ++ ) { if ( factor [ i ] == i ) { for ( int j = i * i ; j < MAX ; j += i ) { if ( factor [ j ] == j ) factor [ j ] = i ; } } } } int calculateNoOFactors ( int n ) { if ( n == 1 ) return 1 ; int ans = 1 ; int dup = factor [ n ] ; int c = 1 ; int j = n / factor [ n ] ; while ( j != 1 ) { if ( factor [ j ] == dup ) c += 1 ; else { dup = factor [ j ] ; ans = ans * ( c + 1 ) ; c = 1 ; } j = j / factor [ j ] ; } ans = ans * ( c + 1 ) ; return ans ; } int main ( ) { generatePrimeFactors ( ) ; int a [ ] = { 10 , 30 , 100 , 450 , 987 } ; int q = sizeof ( a ) / sizeof ( a [ 0 ] ) ; for ( int i = 0 ; i < q ; i ++ ) cout << calculateNoOFactors ( a [ i ] ) << " ▁ " ; return 0 ; }
Digit | CPP program for Digit Product Sequence ; function to produce and print Digit Product Sequence ; Array which store sequence ; Temporary variable to store product ; Initialize first element of the array with 1 ; Run a loop from 1 to N . Check if previous number is single digit or not . If yes then product = 1 else take modulus . Then again check if previous number is single digit or not if yes then store previous number , else store its first value Then for every i store value in the array . ; Print sequence ; Driver Code ; Value of N ; Calling function
#include <bits/stdc++.h> NEW_LINE using namespace std ; void digit_product_Sum ( int N ) { int a [ N ] ; int product = 1 ; a [ 0 ] = 1 ; for ( int i = 1 ; i <= N ; i ++ ) { product = a [ i - 1 ] / 10 ; if ( product == 0 ) product = 1 ; else product = a [ i - 1 ] % 10 ; int val = a [ i - 1 ] / 10 ; if ( val == 0 ) val = a [ i - 1 ] ; a [ i ] = a [ i - 1 ] + ( val * product ) ; } for ( int i = 0 ; i < N ; i ++ ) cout << a [ i ] << " ▁ " ; } int main ( ) { int N = 10 ; digit_product_Sum ( N ) ; return 0 ; }
Geometric mean ( Two Methods ) | Program to calculate the geometric mean of the given array elements . ; function to calculate geometric mean and return float value . ; declare product variable and initialize it to 1. ; Compute the product of all the elements in the array . ; compute geometric mean through formula pow ( product , 1 / n ) and return the value to main function . ; Driver function
#include <bits/stdc++.h> NEW_LINE using namespace std ; float geometricMean ( int arr [ ] , int n ) { float product = 1 ; for ( int i = 0 ; i < n ; i ++ ) product = product * arr [ i ] ; float gm = pow ( product , ( float ) 1 / n ) ; return gm ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << geometricMean ( arr , n ) ; return 0 ; }
Check whether a number can be expressed as a product of single digit numbers | C ++ implementation to check whether a number can be expressed as a product of single digit numbers ; Number of single digit prime numbers ; function to check whether a number can be expressed as a product of single digit numbers ; if ' n ' is a single digit number , then it can be expressed ; define single digit prime numbers array ; repeatedly divide ' n ' by the given prime numbers until all the numbers are used or ' n ' > 1 ; if true , then ' n ' can be expressed ; Driver program to test above
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define SIZE 4 NEW_LINE bool productOfSingelDgt ( int n ) { if ( n >= 0 && n <= 9 ) return true ; int prime [ ] = { 2 , 3 , 5 , 7 } ; for ( int i = 0 ; i < SIZE && n > 1 ; i ++ ) while ( n % prime [ i ] == 0 ) n = n / prime [ i ] ; return ( n == 1 ) ; } int main ( ) { int n = 24 ; productOfSingelDgt ( n ) ? cout << " Yes " : cout << " No " ; return 0 ; }
Program to find sum of first n natural numbers | Efficient CPP program to find sum of first n natural numbers . ; Returns sum of first n natural numbers ; Driver code
#include <iostream> NEW_LINE using namespace std ; int findSum ( int n ) { return n * ( n + 1 ) / 2 ; } int main ( ) { int n = 5 ; cout << findSum ( n ) ; return 0 ; }
Program to find sum of first n natural numbers | Efficient CPP program to find sum of first n natural numbers that avoids overflow if result is going to be within limits . ; Returns sum of first n natural numbers ; If n is odd , ( n + 1 ) must be even ; Driver code
#include <iostream> NEW_LINE using namespace std ; int findSum ( int n ) { if ( n % 2 == 0 ) return ( n / 2 ) * ( n + 1 ) ; else return ( ( n + 1 ) / 2 ) * n ; } int main ( ) { int n = 5 ; cout << findSum ( n ) ; return 0 ; }
Maximum number of unique prime factors | C ++ program to find maximum number of prime factors in first N natural numbers ; Return maximum number of prime factors for any number in [ 1 , N ] ; Based on Sieve of Eratosthenes ; If p is prime ; We simply multiply first set of prime numbers while the product is smaller than N . ; Driven Program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxPrimefactorNum ( int N ) { if ( N < 2 ) return 0 ; bool arr [ N + 1 ] ; memset ( arr , true , sizeof ( arr ) ) ; int prod = 1 , res = 0 ; for ( int p = 2 ; p * p <= N ; p ++ ) { if ( arr [ p ] == true ) { for ( int i = p * 2 ; i <= N ; i += p ) arr [ i ] = false ; prod *= p ; if ( prod > N ) return res ; res ++ ; } } return res ; } int main ( ) { int N = 500 ; cout << maxPrimefactorNum ( N ) << endl ; return 0 ; }
Program to print multiplication table of a number | CPP program to print table over a range . ; Driver code ; Change here to change input number ; Change here to change result .
#include <iostream> NEW_LINE using namespace std ; int main ( ) { int n = 8 ; int range = 12 ; for ( int i = 1 ; i <= range ; ++ i ) cout << n << " ▁ * ▁ " << i << " ▁ = ▁ " << n * i << endl ; return 0 ; }
To check a number is palindrome or not without using any extra space | C ++ program to find number is palindrome or not without using any extra space ; Function to check if given number is palindrome or not without using the extra space ; Find the appropriate divisor to extract the leading digit ; If first and last digit not same return false ; Removing the leading and trailing digit from number ; Reducing divisor by a factor of 2 as 2 digits are dropped ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPalindrome ( int ) ; bool isPalindrome ( int n ) { int divisor = 1 ; while ( n / divisor >= 10 ) divisor *= 10 ; while ( n != 0 ) { int leading = n / divisor ; int trailing = n % 10 ; if ( leading != trailing ) return false ; n = ( n % divisor ) / 10 ; divisor = divisor / 100 ; } return true ; } int main ( ) { isPalindrome ( 1001 ) ? cout << " Yes , ▁ it ▁ is ▁ Palindrome " : cout << " No , ▁ not ▁ Palindrome " ; return 0 ; }
Find whether a given integer is a power of 3 or not | C ++ program to check if a number is power of 3 or not . ; Returns true if n is power of 3 , else false ; The maximum power of 3 value that integer can hold is 1162261467 ( 3 ^ 19 ) . ; Driver code
#include <iostream> NEW_LINE using namespace std ; bool check ( int n ) { if ( n <= 0 ) return false ; return 1162261467 % n == 0 ; } int main ( ) { int n = 9 ; if ( check ( n ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Demlo number ( Square of 11. . .1 ) | CPP program to print DemloNumber ; To return demlo number . This function assumes that the length of str is smaller than 10. ; Add numbers to res upto size of str and then add number reverse to it ; Driver program to test printDemlo ( )
#include <bits/stdc++.h> NEW_LINE using namespace std ; string printDemlo ( string str ) { int len = str . length ( ) ; string res = " " ; for ( int i = 1 ; i <= len ; i ++ ) res += char ( i + '0' ) ; for ( int i = len - 1 ; i >= 1 ; i -- ) res += char ( i + '0' ) ; return res ; } int main ( ) { string str = "111111" ; cout << printDemlo ( str ) ; return 0 ; }
Discrete Cosine Transform ( Algorithm and Program ) | CPP program to perform discrete cosine transform ; Function to find discrete cosine transform and print it ; dct will store the discrete cosine transform ; ci and cj depends on frequency as well as number of row and columns of specified matrix ; sum will temporarily store the sum of cosine signals ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define pi 3.142857 NEW_LINE const int m = 8 , n = 8 ; int dctTransform ( int matrix [ ] [ n ] ) { int i , j , k , l ; float dct [ m ] [ n ] ; float ci , cj , dct1 , sum ; for ( i = 0 ; i < m ; i ++ ) { for ( j = 0 ; j < n ; j ++ ) { if ( i == 0 ) ci = 1 / sqrt ( m ) ; else ci = sqrt ( 2 ) / sqrt ( m ) ; if ( j == 0 ) cj = 1 / sqrt ( n ) ; else cj = sqrt ( 2 ) / sqrt ( n ) ; sum = 0 ; for ( k = 0 ; k < m ; k ++ ) { for ( l = 0 ; l < n ; l ++ ) { dct1 = matrix [ k ] [ l ] * cos ( ( 2 * k + 1 ) * i * pi / ( 2 * m ) ) * cos ( ( 2 * l + 1 ) * j * pi / ( 2 * n ) ) ; sum = sum + dct1 ; } } dct [ i ] [ j ] = ci * cj * sum ; } } for ( i = 0 ; i < m ; i ++ ) { for ( j = 0 ; j < n ; j ++ ) { printf ( " % f TABSYMBOL " , dct [ i ] [ j ] ) ; } printf ( " STRNEWLINE " ) ; } } int main ( ) { int matrix [ m ] [ n ] = { { 255 , 255 , 255 , 255 , 255 , 255 , 255 , 255 } , { 255 , 255 , 255 , 255 , 255 , 255 , 255 , 255 } , { 255 , 255 , 255 , 255 , 255 , 255 , 255 , 255 } , { 255 , 255 , 255 , 255 , 255 , 255 , 255 , 255 } , { 255 , 255 , 255 , 255 , 255 , 255 , 255 , 255 } , { 255 , 255 , 255 , 255 , 255 , 255 , 255 , 255 } , { 255 , 255 , 255 , 255 , 255 , 255 , 255 , 255 } , { 255 , 255 , 255 , 255 , 255 , 255 , 255 , 255 } } ; dctTransform ( matrix ) ; return 0 ; }
Number of times a number can be replaced by the sum of its digits until it only contains one digit | C ++ program to count number of times we need to add digits to get a single digit . ; Here the count variable store how many times we do sum of digits and temporary_sum always store the temporary sum we get at each iteration . ; In this loop we always compute the sum of digits in temporary_ sum variable and convert it into string str till its length become 1 and increase the count in each iteration . ; computing sum of its digits ; converting temporary_sum into string str again . ; increase the count ; Driver program to test the above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int NumberofTimes ( string str ) { int temporary_sum = 0 , count = 0 ; while ( str . length ( ) > 1 ) { temporary_sum = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) temporary_sum += ( str [ i ] - '0' ) ; str = to_string ( temporary_sum ) ; count ++ ; } return count ; } int main ( ) { string s = "991" ; cout << NumberofTimes ( s ) ; return 0 ; }
Climb n | C ++ program to count total number of ways to reach n - th stair with all jumps allowed ; Function to calculate leaps ; Driver code
#include <iostream> NEW_LINE int calculateLeaps ( int n ) { if ( n == 0 n == 1 ) { return 1 ; } else { int leaps = 0 ; for ( int i = 0 ; i < n ; i ++ ) leaps += calculateLeaps ( i ) ; return leaps ; } } int main ( ) { int calculateLeaps ( int ) ; std :: cout << calculateLeaps ( 4 ) << std :: endl ; return 0 ; }
Print last k digits of a ^ b ( a raised to power b ) | C ++ code to find last k digits of a ^ b ; Iterative Function to calculate ( x ^ y ) % p in O ( log y ) ; Initialize result ; x = x % p ; Update x if it is more than or equal to p ; If y is odd , multiply x with result ; y must be even now y = y >> 1 ; y = y / 2 ; C ++ function to calculate number of digits in x ; C ++ function to print last k digits of a ^ b ; Generating 10 ^ k ; Calling modular exponentiation ; Printing leftmost zeros . Since ( a ^ b ) % k can have digits less then k . In that case we need to print zeros ; If temp is not zero then print temp If temp is zero then already printed ; Driver program to test above functions
#include <iostream> NEW_LINE using namespace std ; int power ( long long int x , long long int y , long long int p ) { long long int res = 1 ; while ( y > 0 ) { if ( y & 1 ) res = ( res * x ) % p ; x = ( x * x ) % p ; } return res ; } int numberOfDigits ( int x ) { int i = 0 ; while ( x ) { x /= 10 ; i ++ ; } return i ; } void printLastKDigits ( int a , int b , int k ) { cout << " Last ▁ " << k ; cout << " ▁ digits ▁ of ▁ " << a ; cout << " ^ " << b << " ▁ = ▁ " ; int temp = 1 ; for ( int i = 1 ; i <= k ; i ++ ) temp *= 10 ; temp = power ( a , b , temp ) ; for ( int i = 0 ; i < k - numberOfDigits ( temp ) ; i ++ ) cout << 0 ; if ( temp ) cout << temp ; } int main ( ) { int a = 11 ; int b = 3 ; int k = 2 ; printLastKDigits ( a , b , k ) ; return 0 ; }
Adam Number | CPP program to check Adam Number ; To reverse Digits of numbers ; To square number ; To check Adam Number ; Square first number and square reverse digits of second number ; If reverse of b equals a then given number is Adam number ; Driver program to test above functions
#include <bits/stdc++.h> NEW_LINE using namespace std ; int reverseDigits ( int num ) { int rev = 0 ; while ( num > 0 ) { rev = rev * 10 + num % 10 ; num /= 10 ; } return rev ; } int square ( int num ) { return ( num * num ) ; } bool checkAdamNumber ( int num ) { int a = square ( num ) ; int b = square ( reverseDigits ( num ) ) ; if ( a == reverseDigits ( b ) ) return true ; return false ; } int main ( ) { int num = 12 ; if ( checkAdamNumber ( num ) ) cout << " Adam ▁ Number " ; else cout << " Not ▁ a ▁ Adam ▁ Number " ; return 0 ; }
Compute the parity of a number using XOR and table look | CPP program to illustrate Compute the parity of a number using XOR ; Generating the look - up table while pre - processing ; LOOK_UP is the macro expansion to generate the table ; Function to find the parity ; Number is considered to be of 32 bits ; Dividing the number into 8 - bit chunks while performing X - OR ; Masking the number with 0xff ( 11111111 ) to produce valid 8 - bit result ; Driver code ; Result is 1 for odd parity , 0 for even parity ; Printing the desired result
#include <bits/stdc++.h> NEW_LINE #define P2 ( n ) n, n ^ 1, n ^ 1, n NEW_LINE #define P4 ( n ) P2(n), P2(n ^ 1), P2(n ^ 1), P2(n) NEW_LINE #define P6 ( n ) P4(n), P4(n ^ 1), P4(n ^ 1), P4(n) NEW_LINE #define LOOK_UP P6(0), P6(1), P6(1), P6(0) NEW_LINE unsigned int table [ 256 ] = { LOOK_UP } ; int Parity ( int num ) { int max = 16 ; while ( max >= 8 ) { num = num ^ ( num >> max ) ; max = max / 2 ; } return table [ num & 0xff ] ; } int main ( ) { unsigned int num = 1742346774 ; bool result = Parity ( num ) ; result ? std :: cout << " Odd ▁ Parity " : std :: cout << " Even ▁ Parity " ; return 0 ; }
Count total number of digits from 1 to n | C ++ program to count total number of digits we have to write from 1 to n ; number_of_digits store total digits we have to write ; In the loop we are decreasing 0 , 9 , 99 ... from n till ( n - i + 1 ) is greater than 0 and sum them to number_of_digits to get the required sum ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int totalDigits ( int n ) { int number_of_digits = 0 ; for ( int i = 1 ; i <= n ; i *= 10 ) number_of_digits += ( n - i + 1 ) ; return number_of_digits ; } int main ( ) { int n = 13 ; cout << totalDigits ( n ) << endl ; return 0 ; }
Numbers with exactly 3 divisors | C ++ program to print all three - primes smaller than or equal to n using Sieve of Eratosthenes ; Generates all primes upto n and prints their squares ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; print squares of primes upto n . ; Driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; void numbersWith3Divisors ( int n ) { bool prime [ n + 1 ] ; memset ( prime , true , sizeof ( prime ) ) ; prime [ 0 ] = prime [ 1 ] = 0 ; for ( int p = 2 ; p * p <= n ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * 2 ; i <= n ; i += p ) prime [ i ] = false ; } } cout << " Numbers ▁ with ▁ 3 ▁ divisors ▁ : STRNEWLINE " ; for ( int i = 0 ; i * i <= n ; i ++ ) if ( prime [ i ] ) cout << i * i << " ▁ " ; } int main ( ) { int n = 96 ; numbersWith3Divisors ( n ) ; return 0 ; }
Program for decimal to hexadecimal conversion | C ++ program to convert a decimal number to hexadecimal number ; function to convert decimal to hexadecimal ; char array to store hexadecimal number ; counter for hexadecimal number array ; temporary variable to store remainder ; storing remainder in temp variable . ; check if temp < 10 ; printing hexadecimal number array in reverse order ; Driver program to test above function
#include <iostream> NEW_LINE using namespace std ; void decToHexa ( int n ) { char hexaDeciNum [ 100 ] ; int i = 0 ; while ( n != 0 ) { int temp = 0 ; temp = n % 16 ; if ( temp < 10 ) { hexaDeciNum [ i ] = temp + 48 ; i ++ ; } else { hexaDeciNum [ i ] = temp + 55 ; i ++ ; } n = n / 16 ; } for ( int j = i - 1 ; j >= 0 ; j -- ) cout << hexaDeciNum [ j ] ; } int main ( ) { int n = 2545 ; decToHexa ( n ) ; return 0 ; }
Program for Decimal to Binary Conversion | C ++ program to convert a decimal number to binary number ; function to convert decimal to binary ; array to store binary number ; counter for binary array ; storing remainder in binary array ; printing binary array in reverse order ; Driver program to test above function
#include <iostream> NEW_LINE using namespace std ; void decToBinary ( int n ) { int binaryNum [ 32 ] ; int i = 0 ; while ( n > 0 ) { binaryNum [ i ] = n % 2 ; n = n / 2 ; i ++ ; } for ( int j = i - 1 ; j >= 0 ; j -- ) cout << binaryNum [ j ] ; } int main ( ) { int n = 17 ; decToBinary ( n ) ; return 0 ; }
Break the number into three parts | C ++ program to count number of ways to break a number in three parts . ; Function to count number of ways to make the given number n ; Driver Function
#include <bits/stdc++.h> NEW_LINE #define ll long long int NEW_LINE using namespace std ; ll count_of_ways ( ll n ) { ll count ; count = ( n + 1 ) * ( n + 2 ) / 2 ; return count ; } int main ( ) { ll n = 3 ; cout << count_of_ways ( n ) << endl ; return 0 ; }
Implement * , | CPP code to illustrate * , - , / using only ' + ' arithmetic operator ; Function to flip the sign using only " + " operator ( It is simple with ' * ' allowed . We need to do a = ( - 1 ) * a ; If sign is + ve turn it - ve and vice - versa ; Check if a and b are of different signs ; Function to subtract two numbers by negating b and adding them ; Negating b ; Function to multiply a by b by adding a to itself b times ; because algo is faster if b < a ; Adding a to itself b times ; Check if final sign must be - ve or + ve ; Function to divide a by b by counting how many times ' b ' can be subtracted from ' a ' before getting 0 ; Raise exception if b is 0 ; Negating b to subtract from a ; Subtracting divisor from dividend ; Check if a and b are of similar symbols or not ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int flipSign ( int a ) { int neg = 0 ; int tmp = a < 0 ? 1 : -1 ; while ( a != 0 ) { neg += tmp ; a += tmp ; } return neg ; } bool areDifferentSign ( int a , int b ) { return ( ( a < 0 && b > 0 ) || ( a > 0 && b < 0 ) ) ; } int sub ( int a , int b ) { return a + flipSign ( b ) ; } int mul ( int a , int b ) { if ( a < b ) return mul ( b , a ) ; int sum = 0 ; for ( int i = abs ( b ) ; i > 0 ; i -- ) sum += a ; if ( b < 0 ) sum = flipSign ( sum ) ; return sum ; } int division ( int a , int b ) { if ( b == 0 ) throw ( b ) ; int quotient = 0 , dividend ; int divisor = flipSign ( abs ( b ) ) ; for ( dividend = abs ( a ) ; dividend >= abs ( divisor ) ; dividend += divisor ) quotient ++ ; if ( areDifferentSign ( a , b ) ) quotient = flipSign ( quotient ) ; return quotient ; } int main ( ) { cout << " Subtraction ▁ is ▁ " << sub ( 4 , -2 ) << endl ; cout << " Product ▁ is ▁ " << mul ( -9 , 6 ) << endl ; try { cout << " Division ▁ is ▁ " << division ( 8 , 2 ) ; } catch ( int k ) { cout << " ▁ Exception ▁ : - ▁ Divide ▁ by ▁ 0" ; } return 0 ; }
Number of Groups of Sizes Two Or Three Divisible By 3 | Program to find groups of 2 or 3 whose sum is divisible by 3 ; Initialize groups to 0 ; Increment group with specified remainder ; Return groups using the formula ; Driver Function
#include <iostream> NEW_LINE using namespace std ; int numOfCombinations ( int arr [ ] , int N ) { int C [ 3 ] = { 0 , 0 , 0 } ; for ( int i = 0 ; i < N ; ++ i ) ++ C [ arr [ i ] % 3 ] ; return C [ 1 ] * C [ 2 ] + C [ 0 ] * ( C [ 0 ] - 1 ) / 2 + C [ 0 ] * ( C [ 0 ] - 1 ) * ( C [ 0 ] - 2 ) / 6 + C [ 1 ] * ( C [ 1 ] - 1 ) * ( C [ 1 ] - 2 ) / 6 + C [ 2 ] * ( C [ 2 ] - 1 ) * ( C [ 2 ] - 2 ) / 6 + C [ 0 ] * C [ 1 ] * C [ 2 ] ; } int main ( ) { int arr1 [ 6 ] = { 1 , 5 , 7 , 2 , 9 , 14 } ; cout << numOfCombinations ( arr1 , 6 ) << " STRNEWLINE " ; int arr2 [ 4 ] = { 3 , 6 , 9 , 12 } ; cout << numOfCombinations ( arr2 , 4 ) << " STRNEWLINE " ; return 0 ; }
Check if a number can be written as a sum of ' k ' prime numbers | C ++ implementation to check if N can be written as sum of k primes ; Checking if a number is prime or not ; check for numbers from 2 to sqrt ( x ) if it is divisible return false ; Returns true if N can be written as sum of K primes ; N < 2 K directly return false ; If K = 1 return value depends on primality of N ; if N is even directly return true ; ; If N is odd , then one prime must be 2. All other primes are odd and cannot have a pair sum as even . ; If K >= 3 return true ; ; Driver function
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isprime ( int x ) { for ( int i = 2 ; i * i <= x ; i ++ ) if ( x % i == 0 ) return false ; return true ; } bool isSumOfKprimes ( int N , int K ) { if ( N < 2 * K ) return false ; if ( K == 1 ) return isprime ( N ) ; if ( K == 2 ) { if ( N % 2 == 0 ) return true ; return isprime ( N - 2 ) ; } return true ; } int main ( ) { int n = 10 , k = 2 ; if ( isSumOfKprimes ( n , k ) ) cout << " Yes " << endl ; else cout << " No " << endl ; return 0 ; }
Count total divisors of A or B in a given range | C ++ program to count total divisors of ' a ' or ' b ' in a given range ; Utility function to find LCM of two numbers ; Function to calculate all divisors in given range ; Find LCM of a and b ; Find common divisor by using LCM ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int FindLCM ( int a , int b ) { return ( a * b ) / __gcd ( a , b ) ; } int rangeDivisor ( int m , int n , int a , int b ) { int lcm = FindLCM ( a , b ) ; int a_divisor = n / a - ( m - 1 ) / a ; int b_divisor = n / b - ( m - 1 ) / b ; int common_divisor = n / lcm - ( m - 1 ) / lcm ; int ans = a_divisor + b_divisor - common_divisor ; return ans ; } int main ( ) { int m = 3 , n = 11 , a = 2 , b = 3 ; cout << rangeDivisor ( m , n , a , b ) << endl ; m = 11 , n = 1000000 , a = 6 , b = 35 ; cout << rangeDivisor ( m , n , a , b ) ; return 0 ; }
Numbers having Unique ( or Distinct ) digits | C ++ implementation to find unique digit numbers in a range ; Function to print unique digit numbers in range from l to r . ; Start traversing the numbers ; Find digits and maintain its hash ; if a digit occurs more than 1 time then break ; num will be 0 only when above loop doesn 't get break that means the number is unique so print it. ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printUnique ( int l , int r ) { for ( int i = l ; i <= r ; i ++ ) { int num = i ; bool visited [ 10 ] = { false } ; while ( num ) { if ( visited [ num % 10 ] ) break ; visited [ num % 10 ] = true ; num = num / 10 ; } if ( num == 0 ) cout << i << " ▁ " ; } } int main ( ) { int l = 1 , r = 20 ; printUnique ( l , r ) ; return 0 ; }
Fibonacci modulo p | C ++ program to find minimal 0 Fibonacci for a prime number p ; Returns position of first Fibonacci number whose modulo p is 0. ; add previous two remainders and then take its modulo p . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findMinZero ( int p ) { int first = 1 , second = 1 , number = 2 , next = 1 ; while ( next ) { next = ( first + second ) % p ; first = second ; second = next ; number ++ ; } return number ; } int main ( ) { int p = 7 ; cout << " Minimal ▁ zero ▁ is : ▁ " << findMinZero ( p ) << endl ; return 0 ; }
Perfect cubes in a range | A Simple Method to count cubes between a and b ; Traverse through all numbers in given range and one by one check if number is prime ; Check if current number ' i ' is perfect cube ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printCubes ( int a , int b ) { for ( int i = a ; i <= b ; i ++ ) { for ( int j = 1 ; j * j * j <= i ; j ++ ) { if ( j * j * j == i ) { cout << j * j * j << " ▁ " ; break ; } } } } int main ( ) { int a = 1 , b = 100 ; cout << " Perfect ▁ cubes ▁ in ▁ given ▁ range : STRNEWLINE ▁ " ; printCubes ( a , b ) ; return 0 ; }
Converting a Real Number ( between 0 and 1 ) to Binary String | C ++ program to Binary real number to String . ; Function to convert Binary real number to String ; Check if the number is Between 0 to 1 or Not ; Setting a limit on length : 32 characters . ; compare the number to .5 ; Now it become 0.25 ; Driver code ; Input value
#include <iostream> NEW_LINE #include <string> NEW_LINE using namespace std ; string toBinary ( double n ) { if ( n >= 1 n <= 0 ) return " ERROR " ; string answer ; double frac = 0.5 ; answer . append ( " . " ) ; while ( n > 0 ) { if ( answer . length ( ) >= 32 ) return " ERROR " ; if ( n >= frac ) { answer . append ( "1" ) ; n = n - frac ; } else { answer . append ( "0" ) ; } frac /= 2 ; } return answer ; } int main ( ) { double n = 0.625 ; string result = toBinary ( n ) ; cout << " ( 0" << result << " ) ▁ in ▁ base ▁ 2" << endl ; double m = 0.72 ; result = toBinary ( m ) ; cout << " ( " << result << " ) " << endl ; }
Given a number n , find the first k digits of n ^ n | C ++ program to find the first k digits of n ^ n ; function that manually calculates n ^ n and then removes digits until k digits remain ; loop will terminate when there are only k digits left ; driver function
#include <bits/stdc++.h> NEW_LINE using namespace std ; unsigned long long firstkdigits ( int n , int k ) { unsigned long long product = 1 ; for ( int i = 0 ; i < n ; i ++ ) product *= n ; while ( ( int ) ( product / pow ( 10 , k ) ) != 0 ) product = product / 10 ; return product ; } int main ( ) { int n = 15 ; int k = 4 ; cout << firstkdigits ( n , k ) ; return 0 ; }
Check if a large number is divisible by 9 or not | C ++ program to find if a number is divisible by 9 or not ; Function to find that number divisible by 9 or not ; Compute sum of digits ; Check if sum of digits is divisible by 9. ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int check ( string str ) { int n = str . length ( ) ; int digitSum = 0 ; for ( int i = 0 ; i < n ; i ++ ) digitSum += ( str [ i ] - '0' ) ; return ( digitSum % 9 == 0 ) ; } int main ( ) { string str = "99333" ; check ( str ) ? cout << " Yes " : cout << " No ▁ " ; return 0 ; }
XOR of all subarray XORs | Set 1 | C ++ program to get total xor of all subarray xors ; Returns XOR of all subarray xors ; initialize result by 0 as ( a xor 0 = a ) ; select the starting element ; select the eNding element ; Do XOR of elements in current subarray ; Driver code to test above methods
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getTotalXorOfSubarrayXors ( int arr [ ] , int N ) { int res = 0 ; for ( int i = 0 ; i < N ; i ++ ) for ( int j = i ; j < N ; j ++ ) for ( int k = i ; k <= j ; k ++ ) res = res ^ arr [ k ] ; return res ; } int main ( ) { int arr [ ] = { 3 , 5 , 2 , 4 , 6 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << getTotalXorOfSubarrayXors ( arr , N ) ; return 0 ; }
XOR of all subarray XORs | Set 1 | C ++ program to get total xor of all subarray xors ; Returns XOR of all subarray xors ; initialize result by 0 as ( a XOR 0 = a ) ; loop over all elements once ; get the frequency of current element ; if frequency is odd , then include it in the result ; return the result ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getTotalXorOfSubarrayXors ( int arr [ ] , int N ) { int res = 0 ; for ( int i = 0 ; i < N ; i ++ ) { int freq = ( i + 1 ) * ( N - i ) ; if ( freq % 2 == 1 ) res = res ^ arr [ i ] ; } return res ; } int main ( ) { int arr [ ] = { 3 , 5 , 2 , 4 , 6 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << getTotalXorOfSubarrayXors ( arr , N ) ; return 0 ; }
GCD of more than two ( or array ) numbers | C ++ program to find GCD of two or more numbers ; Function to return gcd of a and b ; Function to find gcd of array of numbers ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int gcd ( int a , int b ) { if ( a == 0 ) return b ; return gcd ( b % a , a ) ; } int findGCD ( int arr [ ] , int n ) { int result = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { result = gcd ( arr [ i ] , result ) ; if ( result == 1 ) { return 1 ; } } return result ; } int main ( ) { int arr [ ] = { 2 , 4 , 6 , 8 , 16 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findGCD ( arr , n ) << endl ; return 0 ; }
GCD of more than two ( or array ) numbers | ; recursive implementation ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int GcdOfArray ( vector < int > & arr , int idx ) { if ( idx == arr . size ( ) - 1 ) { return arr [ idx ] ; } int a = arr [ idx ] ; int b = GcdOfArray ( arr , idx + 1 ) ; return __gcd ( a , b ) ; } int main ( ) { vector < int > arr = { 1 , 2 , 3 } ; cout << GcdOfArray ( arr , 0 ) << " STRNEWLINE " ; arr = { 2 , 4 , 6 , 8 } ; cout << GcdOfArray ( arr , 0 ) << " STRNEWLINE " ; return 0 ; }
Superperfect Number | C ++ program to check whether number is superperfect or not ; Function to calculate sum of all divisors ; Final result of summation of divisors ; find all divisors which divides ' num ' ; if ' i ' is divisor of ' num ' ; if both divisors are same then add it only once else add both ; Returns true if n is Super Perfect else false . ; Find the sum of all divisors of number n ; Again find the sum of all divisors of n1 and check if sum is equal to n1 ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int divSum ( int num ) { int result = 0 ; for ( int i = 1 ; i * i <= num ; ++ i ) { if ( num % i == 0 ) { if ( i == ( num / i ) ) result += i ; else result += ( i + num / i ) ; } } return result ; } bool isSuperPerfect ( int n ) { int n1 = divSum ( n ) ; return ( 2 * n == divSum ( n1 ) ) ; } int main ( ) { int n = 16 ; cout << ( isSuperPerfect ( n ) ? " Yes STRNEWLINE " : " No STRNEWLINE " ) ; n = 6 ; cout << ( isSuperPerfect ( n ) ? " Yes STRNEWLINE " : " No STRNEWLINE " ) ; return 0 ; }
Refactorable number | C ++ program to check whether number is refactorable or not ; Function to count all divisors ; Initialize result ; If divisors are equal , count only one . ; Otherwise count both ; Driver Code
#include <bits/stdc++.h> NEW_LINE bool isRefactorableNumber ( int n ) { int divCount = 0 ; for ( int i = 1 ; i <= sqrt ( n ) ; ++ i ) { if ( n % i == 0 ) { if ( n / i == i ) ++ divCount ; else divCount += 2 ; } } return n % divCount == 0 ; } int main ( ) { int n = 8 ; if ( isRefactorableNumber ( n ) ) puts ( " yes " ) ; else puts ( " no " ) ; n = 14 ; if ( isRefactorableNumber ( n ) ) puts ( " yes " ) ; else puts ( " no " ) ; return 0 ; }
Count all perfect divisors of a number | Below is C ++ code to count total perfect Divisors ; Utility function to check perfect square number ; Returns count all perfect divisors of n ; Initialize result ; Consider every number that can be a divisor of n ; If i is a divisor ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPerfectSquare ( int n ) { int sq = ( int ) sqrt ( n ) ; return ( n == sq * sq ) ; } int countPerfectDivisors ( int n ) { int count = 0 ; for ( int i = 1 ; i * i <= n ; ++ i ) { if ( n % i == 0 ) { if ( isPerfectSquare ( i ) ) ++ count ; if ( n / i != i && isPerfectSquare ( n / i ) ) ++ count ; } } return count ; } int main ( ) { int n = 16 ; cout << " Total ▁ perfect ▁ divisors ▁ of ▁ " << n << " ▁ = ▁ " << countPerfectDivisors ( n ) << " STRNEWLINE " ; n = 12 ; cout << " Total ▁ perfect ▁ divisors ▁ of ▁ " << n << " ▁ = ▁ " << countPerfectDivisors ( n ) ; return 0 ; }
Nearest element with at | C ++ program to print nearest element with at least one common prime factor . ; Loop covers the every element of arr [ ] ; Loop that covers from 0 to i - 1 and i + 1 to n - 1 indexes simultaneously ; print position of closest element ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void nearestGcd ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; ++ i ) { int closest = -1 ; for ( int j = i - 1 , k = i + 1 ; j > 0 k <= n ; -- j , ++ k ) { if ( j >= 0 && __gcd ( arr [ i ] , arr [ j ] ) > 1 ) { closest = j + 1 ; break ; } if ( k < n && __gcd ( arr [ i ] , arr [ k ] ) > 1 ) { closest = k + 1 ; break ; } } cout << closest << " ▁ " ; } } int main ( ) { int arr [ ] = { 2 , 9 , 4 , 3 , 13 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; nearestGcd ( arr , n ) ; return 0 ; }
Largest subsequence having GCD greater than 1 | Efficient C ++ program to find length of the largest subsequence with GCD greater than 1. ; prime [ ] for storing smallest prime divisor of element count [ ] for storing the number of times a particular divisor occurs in a subsequence ; Simple sieve to find smallest prime factors of numbers smaller than MAX ; Prime number will have same divisor ; Returns length of the largest subsequence with GCD more than 1. ; Fetch total unique prime divisor of element ; Increment count [ ] of Every unique divisor we get till now ; Find maximum frequency of divisor ; Driver code ; Pre - compute smallest divisor of all numbers
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 100001 NEW_LINE int prime [ MAX ] , countdiv [ MAX ] ; void SieveOfEratosthenes ( ) { for ( int i = 2 ; i * i <= MAX ; ++ i ) { if ( ! prime [ i ] ) for ( int j = i * 2 ; j <= MAX ; j += i ) prime [ j ] = i ; } for ( int i = 1 ; i < MAX ; ++ i ) if ( ! prime [ i ] ) prime [ i ] = i ; } int largestGCDSubsequence ( int arr [ ] , int n ) { int ans = 0 ; for ( int i = 0 ; i < n ; ++ i ) { int element = arr [ i ] ; while ( element > 1 ) { int div = prime [ element ] ; ++ countdiv [ div ] ; ans = max ( ans , countdiv [ div ] ) ; while ( element % div == 0 ) element /= div ; } } return ans ; } int main ( ) { SieveOfEratosthenes ( ) ; int arr [ ] = { 10 , 15 , 7 , 25 , 9 , 35 } ; int size = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << largestGCDSubsequence ( arr , size ) ; return 0 ; }
Count of Binary Digit numbers smaller than N | C ++ program to count all binary digit numbers smaller than N ; method returns count of binary digit numbers smaller than N ; queue to store all intermediate binary digit numbers ; binary digits start with 1 ; loop until we have element in queue ; push next binary digit numbers only if current popped element is N ; uncomment below line to print actual number in sorted order cout << t << " ▁ " ; ; Driver code to test above methods
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countOfBinaryNumberLessThanN ( int N ) { queue < int > q ; q . push ( 1 ) ; int cnt = 0 ; int t ; while ( ! q . empty ( ) ) { t = q . front ( ) ; q . pop ( ) ; if ( t <= N ) { cnt ++ ; q . push ( t * 10 ) ; q . push ( t * 10 + 1 ) ; } } return cnt ; } int main ( ) { int N = 200 ; cout << countOfBinaryNumberLessThanN ( N ) ; return 0 ; }
Sum of product of x and y such that floor ( n / x ) = y | C ++ program to find sum of product of x and y such that n / x = y ( Integer Division ) ; Return the sum of product x * y . ; Iterating x from 1 to n ; Finding y = n / x . ; Adding product of x and y to answer . ; Driven Program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int sumofproduct ( int n ) { int ans = 0 ; for ( int x = 1 ; x <= n ; x ++ ) { int y = n / x ; ans += ( y * x ) ; } return ans ; } int main ( ) { int n = 10 ; cout << sumofproduct ( n ) << endl ; return 0 ; }
Program for Perrin numbers | Optimized C ++ program for n 'th perrin number ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int per ( int n ) { int a = 3 , b = 0 , c = 2 , i ; int m ; if ( n == 0 ) return a ; if ( n == 1 ) return b ; if ( n == 2 ) return c ; while ( n > 2 ) { m = a + b ; a = b ; b = c ; c = m ; n -- ; } return m ; } int main ( ) { int n = 9 ; cout << per ( n ) ; return 0 ; }
Find the first natural number whose factorial is divisible by x | A cpp program for finding the Special Factorial Number ; function for calculating factorial ; function for check Special_Factorial_Number ; call fact function and the Modulo with k and check if condition is TRUE then return i ; driver function ; taking input
#include <bits/stdc++.h> NEW_LINE #include <boost/multiprecision/cpp_int.hpp> NEW_LINE using boost :: multiprecision :: cpp_int ; using namespace std ; cpp_int fact ( int n ) { cpp_int num = 1 ; for ( int i = 1 ; i <= n ; i ++ ) num = num * i ; return num ; } int Special_Factorial_Number ( int k ) { for ( int i = 1 ; i <= k ; i ++ ) { if ( ( fact ( i ) % k ) == 0 ) { return i ; } } } int main ( ) { int k = 16 ; cout << Special_Factorial_Number ( k ) ; }
Program for Chocolate and Wrapper Puzzle | Efficient C ++ program to find maximum number of chocolates ; Returns maximum number of chocolates we can eat with given money , price of chocolate and number of wrapprices required to get a chocolate . ; Corner case ; First find number of chocolates that can be purchased with the given amount ; Now just add number of chocolates with the chocolates gained by wrapprices ; Driver code ; total money ; cost of each candy ; no of wrappers needs to be ; exchanged for one chocolate .
#include <iostream> NEW_LINE using namespace std ; int countMaxChoco ( int money , int price , int wrap ) { if ( money < price ) return 0 ; int choc = money / price ; choc = choc + ( choc - 1 ) / ( wrap - 1 ) ; return choc ; } int main ( ) { int money = 15 ; int price = 1 ; int wrap = 3 ; cout << countMaxChoco ( money , price , wrap ) ; return 0 ; }
Check if possible to move from given coordinate to desired coordinate | C ++ program to check if it is possible to reach ( a , b ) from ( x , y ) . ; Returns GCD of i and j ; Returns true if it is possible to go to ( a , b ) from ( x , y ) ; Find absolute values of all as sign doesn 't matter. ; If gcd is equal then it is possible to reach . Else not possible . ; Driven Program ; Converting coordinate into positive integer
#include <bits/stdc++.h> NEW_LINE using namespace std ; int gcd ( int i , int j ) { if ( i == j ) return i ; if ( i > j ) return gcd ( i - j , j ) ; return gcd ( i , j - i ) ; } bool ispossible ( int x , int y , int a , int b ) { x = abs ( x ) , y = abs ( y ) , a = abs ( a ) , b = abs ( b ) ; return ( gcd ( x , y ) == gcd ( a , b ) ) ; } int main ( ) { int x = 35 , y = 15 ; int a = 20 , b = 25 ; ( ispossible ( x , y , a , b ) ) ? ( cout << " Yes " ) : ( cout << " No " ) ; return 0 ; }
Equidigital Numbers | C ++ Program to find Equidigital Numbers till n ; Array to store all prime less than and equal to MAX . ; Utility function for sieve of sundaram ; In general Sieve of Sundaram , produces primes smaller than ( 2 * x + 2 ) for a number given number x . Since we want primes smaller than MAX , we reduce MAX to half This array is used to separate numbers of the form i + j + 2 ij from others where 1 <= i <= j ; Main logic of Sundaram . Mark all numbers which do not generate prime number by doing 2 * i + 1 ; Since 2 is a prime number ; Print other primes . Remaining primes are of the form 2 * i + 1 such that marked [ i ] is false . ; Returns true if n is a Equidigital number , else false . ; Count digits in original number ; Count all digits in prime factors of n pDigit is going to hold this value . ; Count powers of p in n ; If primes [ i ] is a prime factor , ; Count the power of prime factors ; Add its digits to pDigit . ; Add digits of power of prime factors to pDigit . ; If n != 1 then one prime factor still to be summed up ; ; If digits in prime factors and digits in original number are same , then return true . Else return false . ; Driver code ; Finding all prime numbers before limit . These numbers are used to find prime factors .
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 10000 ; vector < int > primes ; void sieveSundaram ( ) { bool marked [ MAX / 2 + 1 ] = { 0 } ; for ( int i = 1 ; i <= ( sqrt ( MAX ) - 1 ) / 2 ; i ++ ) for ( int j = ( i * ( i + 1 ) ) << 1 ; j <= MAX / 2 ; j = j + 2 * i + 1 ) marked [ j ] = true ; primes . push_back ( 2 ) ; for ( int i = 1 ; i <= MAX / 2 ; i ++ ) if ( marked [ i ] == false ) primes . push_back ( 2 * i + 1 ) ; } bool isEquidigital ( int n ) { if ( n == 1 ) return true ; int original_no = n ; int sumDigits = 0 ; while ( original_no > 0 ) { sumDigits ++ ; original_no = original_no / 10 ; } int pDigit = 0 , count_exp = 0 , p ; for ( int i = 0 ; primes [ i ] <= n / 2 ; i ++ ) { while ( n % primes [ i ] == 0 ) { p = primes [ i ] ; n = n / p ; count_exp ++ ; } while ( p > 0 ) { pDigit ++ ; p = p / 10 ; } while ( count_exp > 1 ) { pDigit ++ ; count_exp = count_exp / 10 ; } } if ( n != 1 ) { while ( n > 0 ) { pDigit ++ ; n = n / 10 ; } } return ( pDigit == sumDigits ) ; } int main ( ) { sieveSundaram ( ) ; cout << " Printing ▁ first ▁ few ▁ Equidigital ▁ Numbers " " ▁ using ▁ isEquidigital ( ) STRNEWLINE " ; for ( int i = 1 ; i < 20 ; i ++ ) if ( isEquidigital ( i ) ) cout << i << " ▁ " ; return 0 ; }
Maximum sum of distinct numbers with LCM as N | C / C ++ program to get maximum sum of Numbers with condition that their LCM should be N ; Method returns maximum sum f distinct number whose LCM is N ; find all divisors which divides ' N ' ; if ' i ' is divisor of ' N ' ; if both divisors are same then add it only once else add both ; Driver code to test above methods
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getMaximumSumWithLCMN ( int N ) { int sum = 0 ; int LIM = sqrt ( N ) ; for ( int i = 1 ; i <= LIM ; i ++ ) { if ( N % i == 0 ) { if ( i == ( N / i ) ) sum += i ; else sum += ( i + N / i ) ; } } return sum ; } int main ( ) { int N = 12 ; cout << getMaximumSumWithLCMN ( N ) << endl ; return 0 ; }
LCM of First n Natural Numbers | C ++ program to find LCM of First N Natural Numbers . ; to calculate hcf ; to calculate lcm ; lcm ( a , b ) = ( a * b ) / hcf ( a , b ) ; assign a = lcm of n , n - 1 ; b = b - 1 ; Driver code ; base case ; Function call pass n , n - 1 in function to find LCM of first n natural number
#include <bits/stdc++.h> NEW_LINE using namespace std ; int hcf ( int a , int b ) { if ( b == 0 ) return a ; return hcf ( b , a % b ) ; } int findlcm ( int a , int b ) { if ( b == 1 ) return a ; a = ( a * b ) / hcf ( a , b ) ; b -= 1 ; return findlcm ( a , b ) ; } int main ( ) { int n = 7 ; if ( n < 3 ) cout << n ; else cout << findlcm ( n , n - 1 ) ; return 0 ; }
Smallest number divisible by first n numbers | C ++ program to find smallest number evenly divisible by all numbers 1 to n ; Function returns the lcm of first n numbers ; Driver program to test the above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; long long lcm ( long long n ) { long long ans = 1 ; for ( long long i = 1 ; i <= n ; i ++ ) ans = ( ans * i ) / ( __gcd ( ans , i ) ) ; return ans ; } int main ( ) { long long n = 20 ; cout << lcm ( n ) ; return 0 ; }
Trapezoidal Rule for Approximate Value of Definite Integral | C ++ program to implement Trapezoidal rule ; A sample function whose definite integral 's approximate value is computed using Trapezoidal rule ; Declaring the function f ( x ) = 1 / ( 1 + x * x ) ; Function to evaluate the value of integral ; Grid spacing ; Computing sum of first and last terms in above formula ; Adding middle terms in above formula ; h / 2 indicates ( b - a ) / 2 n . Multiplying h / 2 with s . ; Driver program to test above function ; Range of definite integral ; Number of grids . Higher value means more accuracy
#include <stdio.h> NEW_LINE float y ( float x ) { return 1 / ( 1 + x * x ) ; } float trapezoidal ( float a , float b , float n ) { float h = ( b - a ) / n ; float s = y ( a ) + y ( b ) ; for ( int i = 1 ; i < n ; i ++ ) s += 2 * y ( a + i * h ) ; return ( h / 2 ) * s ; } int main ( ) { float x0 = 0 ; float xn = 1 ; int n = 6 ; printf ( " Value ▁ of ▁ integral ▁ is ▁ % 6.4f STRNEWLINE " , trapezoidal ( x0 , xn , n ) ) ; return 0 ; }
Breaking an Integer to get Maximum Product | ; The main function that returns the max possible product ; n equals to 2 or 3 must be handled explicitly ; Keep removing parts of size 3 while n is greater than 4 ; Keep multiplying 3 to res ; The last part multiplied by previous parts ; Driver program to test above functions
#include <iostream> NEW_LINE using namespace std ; int maxProd ( int n ) { if ( n == 2 n == 3 ) return ( n - 1 ) ; int res = 1 ; while ( n > 4 ) { n -= 3 ; res *= 3 ; } return ( n * res ) ; } int main ( ) { cout << " Maximum ▁ Product ▁ is ▁ " << maxProd ( 45 ) ; return 0 ; }
Finding number of digits in n 'th Fibonacci number | C ++ program to find number of digits in nth Fibonacci number ; This function returns the number of digits in nth Fibonacci number after ceiling it Formula used ( n * log ( phi ) - ( log 5 ) / 2 ) ; using phi = 1.6180339887498948 ; Driver program to test the above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; long long numberOfDigits ( long long n ) { if ( n == 1 ) return 1 ; long double d = ( n * log10 ( 1.6180339887498948 ) ) - ( ( log10 ( 5 ) ) / 2 ) ; return ceil ( d ) ; } int main ( ) { long long i ; for ( i = 1 ; i <= 10 ; i ++ ) cout << " Number ▁ of ▁ Digits ▁ in ▁ F ( " << i << " ) ▁ - ▁ " << numberOfDigits ( i ) << " STRNEWLINE " ; return 0 ; }
Number of elements with odd factors in given range | C ++ program to count number of odd squares in given range [ n , m ] ; Function to count odd squares ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countOddSquares ( int n , int m ) { return ( int ) pow ( m , 0.5 ) - ( int ) pow ( n - 1 , 0.5 ) ; } int main ( ) { int n = 5 , m = 100 ; cout << " Count ▁ is ▁ " << countOddSquares ( n , m ) ; return 0 ; }
K 'th Boom Number | C ++ program to find K 'th Boom number ; This function uses queue data structure to K 'th Boom number ; Create an empty queue of strings ; Enqueue an empty string ; counter for K 'th element ; This loop checks the value of count to become equal to K when value of count will be equals to k we will print the Boom number ; current Boom number ; Store current Boom number before changing it ; Append "2" to string s1 and enqueue it ; check if count == k ; K 'th Boom number ; Append "3" to string s2 and enqueue it . Note that s2 contains the previous front ; check if count == k ; K 'th Boom number ; Driver program to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; typedef long long int ll ; void boomNumber ( ll k ) { queue < string > q ; q . push ( " " ) ; ll count = 0 ; while ( count <= k ) { string s1 = q . front ( ) ; q . pop ( ) ; string s2 = s1 ; q . push ( s1 . append ( "2" ) ) ; count ++ ; if ( count == k ) { cout << s1 << endl ; break ; } q . push ( s2 . append ( "3" ) ) ; count ++ ; if ( count == k ) { cout << s2 << endl ; break ; } } return ; } int main ( ) { ll k = 1000000 ; boomNumber ( k ) ; return 0 ; }