text
stringlengths 17
4.49k
| code
stringlengths 49
5.46k
|
---|---|
Nesbitt 's Inequality | C ++ code to verify Nesbitt 's Inequality ; 3 parts of the inequality sum ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isValidNesbitt ( double a , double b , double c ) { double A = a / ( b + c ) ; double B = b / ( a + c ) ; double C = c / ( a + b ) ; double inequality = A + B + C ; return ( inequality >= 1.5 ) ; } int main ( ) { double a = 1.0 , b = 2.0 , c = 3.0 ; if ( isValidNesbitt ( a , b , c ) ) cout << " Nesbitt ' s β inequality β satisfied . " << " for β real β numbers β " << a << " , β " << b << " , β " << c << " STRNEWLINE " ; else cout << " Not β satisfied " ; return 0 ; } |
Ordered Prime Signature | CPP to find total number of divisors of a number , using ordered prime signature ; Finding primes upto entered number ; Finding primes by Sieve of Eratosthenes method ; If prime [ i ] is not changed , then it is prime ; Update all multiples of p ; Forming array of the prime numbers found ; Finding ordered prime signature of the number ; Map to store prime factors and the related exponents ; Declaring an iterator for map ; Finding prime factorization of the number ; Storing the prime factor and its exponent in map ; Storing the exponent in a vector ; Sorting the stored exponents ; Printing the prime signature ; Finding total number of divisors of the number ; Adding one to each element present ; in ordered prime signature ; Multiplying the elements ; Driver Method | #include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > primes ( int n ) { bool prime [ n + 1 ] ; memset ( prime , true , sizeof ( prime ) ) ; for ( int i = 2 ; i * i <= n ; i ++ ) { if ( prime [ i ] == true ) { for ( int j = i * 2 ; j <= n ; j += i ) prime [ j ] = false ; } } vector < int > arr ; for ( int i = 2 ; i <= n ; i ++ ) { if ( prime [ i ] ) arr . push_back ( i ) ; } return arr ; } vector < int > signature ( int n ) { vector < int > r = primes ( n ) ; map < int , int > factor ; map < int , int > :: iterator it ; vector < int > sort_exp ; int k , t = n ; it = factor . begin ( ) ; for ( int i = 0 ; i < r . size ( ) ; i ++ ) { if ( n % r [ i ] == 0 ) { k = 0 ; while ( n % r [ i ] == 0 ) { n = n / r [ i ] ; k ++ ; } factor . insert ( it , pair < int , int > ( r [ i ] , k ) ) ; sort_exp . push_back ( k ) ; } } sort ( sort_exp . begin ( ) , sort_exp . end ( ) ) ; cout << " β The β Ordered β Prime β Signature β of β " << t << " β is β : β STRNEWLINE { β " ; for ( int i = 0 ; i < sort_exp . size ( ) ; i ++ ) { if ( i != sort_exp . size ( ) - 1 ) cout << sort_exp [ i ] << " , β " ; else cout << sort_exp [ i ] << " β } STRNEWLINE " ; } return sort_exp ; } void divisors ( int n ) { int f = 1 , l ; vector < int > div = signature ( n ) ; l = div . size ( ) ; for ( int i = 0 ; i < l ; i ++ ) { div [ i ] += 1 ; f *= div [ i ] ; } cout << " The β total β number β of β divisors β of β " << n << " β is β " << f << " STRNEWLINE " ; } int main ( ) { int n = 13 ; divisors ( n ) ; return 0 ; } |
Cube Free Numbers smaller than n | Efficient C ++ Program to print all cube free numbers smaller than or equal to n . ; Initialize all numbers as not cube free ; Traverse through all possible cube roots ; If i itself is cube free ; Mark all multiples of i as not cube free ; Print all cube free numbers ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printCubeFree ( int n ) { bool cubFree [ n + 1 ] ; for ( int i = 0 ; i <= n ; i ++ ) cubFree [ i ] = true ; for ( int i = 2 ; i * i * i <= n ; i ++ ) { if ( cubFree [ i ] ) { for ( int multiple = 1 ; i * i * i * multiple <= n ; multiple ++ ) { cubFree [ i * i * i * multiple ] = false ; } } } for ( int i = 2 ; i <= n ; i ++ ) { if ( cubFree [ i ] == true ) cout << i << " β " ; } } int main ( ) { printCubeFree ( 20 ) ; return 0 ; } |
Heap Sort for decreasing order using min heap | C ++ program for implementation of Heap Sort ; To heapify a subtree rooted with node i which is an index in arr [ ] . n is size of heap ; Initialize smalles as root ; left = 2 * i + 1 ; right = 2 * i + 2 ; If left child is smaller than root ; If right child is smaller than smallest so far ; If smallest is not root ; Recursively heapify the affected sub - tree ; main function to do heap sort ; Build heap ( rearrange array ) ; One by one extract an element from heap ; Move current root to end ; call max heapify on the reduced heap ; A utility function to print array of size n ; Driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; void heapify ( int arr [ ] , int n , int i ) { int smallest = i ; int l = 2 * i + 1 ; int r = 2 * i + 2 ; if ( l < n && arr [ l ] < arr [ smallest ] ) smallest = l ; if ( r < n && arr [ r ] < arr [ smallest ] ) smallest = r ; if ( smallest != i ) { swap ( arr [ i ] , arr [ smallest ] ) ; heapify ( arr , n , smallest ) ; } } void heapSort ( int arr [ ] , int n ) { for ( int i = n / 2 - 1 ; i >= 0 ; i -- ) heapify ( arr , n , i ) ; for ( int i = n - 1 ; i >= 0 ; i -- ) { swap ( arr [ 0 ] , arr [ i ] ) ; heapify ( arr , i , 0 ) ; } } void printArray ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; ++ i ) cout << arr [ i ] << " β " ; cout << " STRNEWLINE " ; } int main ( ) { int arr [ ] = { 4 , 6 , 3 , 2 , 9 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; heapSort ( arr , n ) ; cout << " Sorted β array β is β STRNEWLINE " ; printArray ( arr , n ) ; } |
Squared triangular number ( Sum of cubes ) | C ++ program to check if a given number is sum of cubes of natural numbers . ; Returns root of n ( n + 1 ) / 2 = num if num is triangular ( or integerroot exists ) . Else returns - 1. ; Considering the equation n * ( n + 1 ) / 2 = num . The equation is : a ( n ^ 2 ) + bn + c = 0 "; ; Find roots of equation ; checking if root1 is natural ; checking if root2 is natural ; Returns square root of x if it is perfect square . Else returns - 1. ; Find floating point value of square root of x . ; If square root is an integer ; Function to find if the given number is sum of the cubes of first n natural numbers ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int isTriangular ( int num ) { if ( num < 0 ) return false ; int c = ( -2 * num ) ; int b = 1 , a = 1 ; int d = ( b * b ) - ( 4 * a * c ) ; if ( d < 0 ) return -1 ; float root1 = ( - b + sqrt ( d ) ) / ( 2 * a ) ; float root2 = ( - b - sqrt ( d ) ) / ( 2 * a ) ; if ( root1 > 0 && floor ( root1 ) == root1 ) return root1 ; if ( root2 > 0 && floor ( root2 ) == root2 ) return root2 ; return -1 ; } int isPerfectSquare ( long double x ) { long double sr = sqrt ( x ) ; if ( ( sr - floor ( sr ) ) == 0 ) return floor ( sr ) ; else return -1 ; } int findS ( int s ) { int sr = isPerfectSquare ( s ) ; if ( sr == -1 ) return -1 ; return isTriangular ( sr ) ; } int main ( ) { int s = 9 ; int n = findS ( s ) ; n == -1 ? cout << " - 1" : cout << n ; return 0 ; } |
Smallest even digits number not less than N | CPP program to print the smallest integer not less than N with all even digits ; function to return the answer when the first odd digit is 9 ; traverse towwars the left to find the non - 8 digit ; index digit ; if digit is not 8 , then break ; if on the left side of the '9' , no 8 is found then we return by adding a 2 and 0 's ; till non - 8 digit add all numbers ; if non - 8 is even or odd than add the next even . ; add 0 to right of 9 ; function to return the smallest number with all digits even ; convert the number to string to perform operations ; find out the first odd number ; if no odd numbers are there , than n is the answer ; if the odd number is 9 , than tricky case handles it ; add all digits till first odd ; increase the odd digit by 1 ; add 0 to the right of the odd number ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int trickyCase ( string s , int index ) { int index1 = -1 ; for ( int i = index - 1 ; i >= 0 ; i -- ) { int digit = s [ i ] - '0' ; if ( digit != 8 ) { index1 = i ; break ; } } if ( index1 == -1 ) return 2 * pow ( 10 , s . length ( ) ) ; int num = 0 ; for ( int i = 0 ; i < index1 ; i ++ ) num = num * 10 + ( s [ i ] - '0' ) ; if ( s [ index1 ] % 2 == 0 ) num = num * 10 + ( s [ index1 ] - '0' + 2 ) ; else num = num * 10 + ( s [ index1 ] - '0' + 1 ) ; for ( int i = index1 + 1 ; i < s . length ( ) ; i ++ ) num = num * 10 ; return num ; } int smallestNumber ( int n ) { int num = 0 ; string s = " " ; int duplicate = n ; while ( n ) { s = char ( n % 10 + 48 ) + s ; n /= 10 ; } int index = -1 ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { int digit = s [ i ] - '0' ; if ( digit & 1 ) { index = i ; break ; } } if ( index == -1 ) return duplicate ; if ( s [ index ] == '9' ) { num = trickyCase ( s , index ) ; return num ; } for ( int i = 0 ; i < index ; i ++ ) num = num * 10 + ( s [ i ] - '0' ) ; num = num * 10 + ( s [ index ] - '0' + 1 ) ; for ( int i = index + 1 ; i < s . length ( ) ; i ++ ) num = num * 10 ; return num ; } int main ( ) { int N = 2397 ; cout << smallestNumber ( N ) ; return 0 ; } |
n | Simple CPP program to find n - th number with sum of digits as 10. ; Find sum of digits in current no . ; If sum is 10 , we increment count ; If count becomes n , we return current number . ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findNth ( int n ) { int count = 0 ; for ( int curr = 19 ; ; curr += 9 ) { int sum = 0 ; for ( int x = curr ; x > 0 ; x = x / 10 ) sum = sum + x % 10 ; if ( sum == 10 ) count ++ ; if ( count == n ) return curr ; } return -1 ; } int main ( ) { printf ( " % d STRNEWLINE " , findNth ( 5 ) ) ; return 0 ; } |
Sum of pairwise products | Simple CPP program to find sum of given series . ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; long long int findSum ( int n ) { long long int sum = 0 ; for ( int i = 1 ; i <= n ; i ++ ) for ( int j = i ; j <= n ; j ++ ) sum = sum + i * j ; return sum ; } int main ( ) { int n = 5 ; cout << findSum ( n ) ; return 0 ; } |
Sum of pairwise products | Efficient CPP program to find sum of given series . ; Sum of multiples of 1 is 1 * ( 1 + 2 + . . ) ; Adding sum of multiples of numbers other than 1 , starting from 2. ; Subtract previous number from current multiple . ; For example , for 2 , we get sum as ( 2 + 3 + 4 + ... . ) * 2 ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; long long int findSum ( int n ) { long long int multiTerms = n * ( n + 1 ) / 2 ; long long int sum = multiTerms ; for ( int i = 2 ; i <= n ; i ++ ) { multiTerms = multiTerms - ( i - 1 ) ; sum = sum + multiTerms * i ; } return sum ; } int main ( ) { int n = 5 ; cout << findSum ( n ) ; return 0 ; } |
Lemoine 's Conjecture | C ++ code to verify Lemoine 's Conjecture for any odd number >= 7 ; Function to check if a number is prime or not ; Representing n as p + ( 2 * q ) to satisfy lemoine 's conjecture ; Declaring a map to hold pairs ( p , q ) ; Declaring an iterator for map ; Finding various values of p for each q to satisfy n = p + ( 2 * q ) ; After finding a pair that satisfies the equation , check if both p and q are prime or not ; If both p and q are prime , store them in the map ; Displaying all pairs ( p , q ) that satisfy lemoine ' s β conjecture β for β the β number β ' n ' ; Driver Function ; Function calling | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPrime ( int n ) { if ( n < 2 ) return false ; for ( int i = 2 ; i <= sqrt ( n ) ; i ++ ) { if ( n % i == 0 ) return false ; } return true ; } void lemoine ( int n ) { map < int , int > pr ; map < int , int > :: iterator it ; it = pr . begin ( ) ; for ( int q = 1 ; q <= n / 2 ; q ++ ) { int p = n - 2 * q ; if ( isPrime ( p ) && isPrime ( q ) ) pr . insert ( it , pair < int , int > ( p , q ) ) ; } for ( it = pr . begin ( ) ; it != pr . end ( ) ; ++ it ) cout << n << " β = β " << it -> first << " β + β ( 2 β * β " << it -> second << " ) STRNEWLINE " ; } int main ( ) { int n = 39 ; cout << n << " β can β be β expressed β as β " << endl ; lemoine ( n ) ; return 0 ; } |
Sum of n digit numbers divisible by a given number | Efficient CPP program to find the sum divisible numbers . ; find the Sum of having n digit and divisible by the number ; compute the first and last term ; first number which is divisible by given number ; last number which is divisible by given number ; total divisible number ; return the total sum ; Driver code | #include <cmath> NEW_LINE #include <iostream> NEW_LINE using namespace std ; int totalSumDivisibleByNum ( int digit , int number ) { int firstnum = pow ( 10 , digit - 1 ) ; int lastnum = pow ( 10 , digit ) ; firstnum = ( firstnum - firstnum % number ) + number ; lastnum = ( lastnum - lastnum % number ) ; int count = ( ( lastnum - firstnum ) / number + 1 ) ; return ( ( lastnum + firstnum ) * count ) / 2 ; } int main ( ) { int n = 3 , number = 7 ; cout << totalSumDivisibleByNum ( n , number ) ; return 0 ; } |
Program for N | CPP Program to find nth term of Arithmetic progression ; using formula to find the Nth term t ( n ) = a ( 1 ) + ( n - 1 ) * d ; Driver code ; starting number ; Common difference ; N th term to be find ; Display the output | #include <bits/stdc++.h> NEW_LINE using namespace std ; int Nth_of_AP ( int a , int d , int N ) { return ( a + ( N - 1 ) * d ) ; } int main ( ) { int a = 2 ; int d = 1 ; int N = 5 ; cout << " The β " << N << " th β term β of β the β series β is β : β " << Nth_of_AP ( a , d , N ) ; return 0 ; } |
Fibbinary Numbers ( No consecutive 1 s in binary ) | CPP program to check if a number is fibinnary number or not ; function to check if binary representation of an integer has consecutive 1 s ; stores the previous last bit initially as 0 ; if current last bit and previous last bit is 1 ; stores the last bit ; right shift the number ; Driver code to check above function | #include <iostream> NEW_LINE using namespace std ; bool checkFibinnary ( int n ) { int prev_last = 0 ; while ( n ) { if ( ( n & 1 ) && prev_last ) return false ; prev_last = n & 1 ; n >>= 1 ; } return true ; } int main ( ) { int n = 10 ; if ( checkFibinnary ( n ) ) cout << " YES " ; else cout << " NO " ; return 0 ; } |
Sum of the series 5 + 55 + 555 + . . up to n terms | C ++ program for sum of the series 5 + 55 + 555. . ... n ; function which return the the sum of series ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int sumOfSeries ( int n ) { return 0.6172 * ( pow ( 10 , n ) - 1 ) - 0.55 * n ; } int main ( ) { int n = 2 ; cout << sumOfSeries ( n ) ; return 0 ; } |
Nonagonal number | CPP Program to find nth nonagonal number . ; Function to find nth nonagonal number . ; Formula to find nth nonagonal number . ; Driver function . | #include <bits/stdc++.h> NEW_LINE using namespace std ; int Nonagonal ( int n ) { return n * ( 7 * n - 5 ) / 2 ; } int main ( ) { int n = 10 ; cout << Nonagonal ( n ) ; return 0 ; } |
Check if a large number is divisible by 20 | CPP program to check if a large number is divisible by 20. ; Get number with last two digits ; Check if the number formed by last two digits is divisible by 5 and 4. ; Driver Program | #include <iostream> NEW_LINE using namespace std ; bool divisibleBy20 ( string num ) { int lastTwoDigits = stoi ( num . substr ( num . length ( ) - 2 , num . length ( ) - 1 ) ) ; return ( ( lastTwoDigits % 5 == 0 ) && ( lastTwoDigits % 4 == 0 ) ) ; } int main ( ) { string num = "63284689320" ; if ( divisibleBy20 ( num ) ) cout << " Yes " << endl ; else cout << " No " << endl ; return 0 ; } |
Divisibility by 12 for a large number | C ++ Program to check if number is divisible by 12 ; if number greater then 3 ; find last digit ; no is odd ; find second last digit ; find sum of all digits ; if number is less then or equal to 100 ; Driver function | #include <iostream> NEW_LINE using namespace std ; bool isDvisibleBy12 ( string num ) { if ( num . length ( ) >= 3 ) { int d1 = ( int ) num [ num . length ( ) - 1 ] ; if ( d1 % 2 != 0 ) return ( 0 ) ; int d2 = ( int ) num [ num . length ( ) - 2 ] ; int sum = 0 ; for ( int i = 0 ; i < num . length ( ) ; i ++ ) sum += num [ i ] ; return ( sum % 3 == 0 && ( d2 * 10 + d1 ) % 4 == 0 ) ; } else { int number = stoi ( num ) ; return ( number % 12 == 0 ) ; } } int main ( ) { string num = "12244824607284961224" ; if ( isDvisibleBy12 ( num ) ) cout << " Yes " << endl ; else cout << " No " << endl ; return 0 ; } |
Largest number that is not a perfect square | CPP program to find the largest non perfect square number among n numbers ; takes the sqrt of the number ; checks if it is a perfect square number ; function to find the largest non perfect square number ; stores the maximum of all non perfect square numbers ; traverse for all elements in the array ; store the maximum if not a perfect square ; driver code to check the above functions ; function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool check ( int n ) { int d = sqrt ( n ) ; if ( d * d == n ) return true ; return false ; } int largestNonPerfectSquareNumber ( int a [ ] , int n ) { int maxi = -1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( ! check ( a [ i ] ) ) maxi = max ( a [ i ] , maxi ) ; } return maxi ; } int main ( ) { int a [ ] = { 16 , 20 , 25 , 2 , 3 , 10 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << largestNonPerfectSquareNumber ( a , n ) ; return 0 ; } |
Program to print Arithmetic Progression series | CPP Program to print an arithmetic progression series ; Printing AP by simply adding d to previous term . ; Driver code ; starting number ; Common difference ; N th term to be find | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printAP ( int a , int d , int n ) { int curr_term ; curr_term = a ; for ( int i = 1 ; i <= n ; i ++ ) { cout << curr_term << " β " ; curr_term = curr_term + d ; } } int main ( ) { int a = 2 ; int d = 1 ; int n = 5 ; printAP ( a , d , n ) ; return 0 ; } |
Program to print non square numbers | CPP program to print first n non square number ; Print curr_count numbers . curr_count is current gap between two square numbers . ; skip a square number . ; Count of next non - square numbers is next even number . ; Driver code | #include <assert.h> NEW_LINE #include <math.h> NEW_LINE #include <stdio.h> NEW_LINE void printNonSquare ( int n ) { int curr_count = 2 , num = 2 , count = 0 ; while ( count < n ) { for ( int i = 0 ; i < curr_count && count < n ; i ++ ) { printf ( " % d β " , num ) ; count ++ ; num ++ ; } num ++ ; curr_count += 2 ; } } int main ( ) { int n = 10 ; printNonSquare ( n ) ; return 0 ; } |
Count number of trailing zeros in product of array | CPP program for count total zero in product of array ; Returns count of zeros in product of array ; count number of 2 s in each element ; count number of 5 s in each element ; return the minimum ; Driven Program | #include <iostream> NEW_LINE using namespace std ; int countZeros ( int a [ ] , int n ) { int count2 = 0 , count5 = 0 ; for ( int i = 0 ; i < n ; i ++ ) { while ( a [ i ] % 2 == 0 ) { a [ i ] = a [ i ] / 2 ; count2 ++ ; } while ( a [ i ] % 5 == 0 ) { a [ i ] = a [ i ] / 5 ; count5 ++ ; } } return ( count2 < count5 ) ? count2 : count5 ; } int main ( ) { int a [ ] = { 10 , 100 , 20 , 30 , 50 , 90 , 12 , 80 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << countZeros ( a , n ) ; return 0 ; } |
Sum of square of first n even numbers | Efficient C ++ method to find sum of square of first n even numbers . ; Driver code | #include <iostream> NEW_LINE using namespace std ; int squareSum ( int n ) { return 2 * n * ( n + 1 ) * ( 2 * n + 1 ) / 3 ; } int main ( ) { cout << squareSum ( 8 ) ; return 0 ; } |
MΓ ΒΌ nchhausen Number | C ++ code for MA14nchhausen Number ; pwr [ i ] is going to store i raised to power i . ; Function to check out whether the number is MA14nchhausen Number or not ; Precompute i raised to power i for every i ; The input here is fixed i . e . it will check up to n ; check the integer for MA14nchhausen Number , if yes then print out the number ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; unsigned pwr [ 10 ] ; bool isMunchhausen ( unsigned n ) { unsigned sum = 0 ; int temp = n ; while ( temp ) { sum += pwr [ ( temp % 10 ) ] ; temp /= 10 ; } return ( sum == n ) ; } void printMunchhausenNumbers ( int n ) { for ( int i = 0 ; i < 10 ; i ++ ) pwr [ i ] = ( unsigned ) pow ( ( float ) i , ( float ) i ) ; for ( unsigned i = 1 ; i <= n ; i ++ ) if ( isMunchhausen ( i ) ) cout << i << " STRNEWLINE " ; } int main ( ) { int n = 10000 ; printMunchhausenNumbers ( n ) ; return 0 ; } |
K | CPP program for finding k - th digit in a ^ b ; To compute k - th digit in a ^ b ; computing a ^ b ; getting last digit ; increasing count by 1 ; if current number is required digit ; remove last digit ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int kthdigit ( int a , int b , int k ) { int p = pow ( a , b ) ; int count = 0 ; while ( p > 0 && count < k ) { int rem = p % 10 ; count ++ ; if ( count == k ) return rem ; p = p / 10 ; } return 0 ; } int main ( ) { int a = 5 , b = 2 ; int k = 1 ; cout << kthdigit ( a , b , k ) ; return 0 ; } |
Recursive sum of digit in n ^ x , where n and x are very large | CPP Code for Sum of digit of n ^ x where n and x are very large ; function to get sum of digits of a number ; function to return sum ; Find sum of digits in n ; Find remainder of exponent ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; long digSum ( long n ) { if ( n == 0 ) return 0 ; return ( n % 9 == 0 ) ? 9 : ( n % 9 ) ; } long PowDigSum ( long n , long x ) { long sum = digSum ( n ) ; long rem = x % 6 ; if ( ( sum == 3 sum == 6 ) && x > 1 ) return 9 ; else if ( x == 1 ) return sum ; else if ( x == 0 ) return 1 ; else if ( rem == 0 ) return digSum ( ( long ) pow ( sum , 6 ) ) ; else return digSum ( ( long ) pow ( sum , rem ) ) ; } int main ( ) { int n = 33333 ; int x = 332654 ; cout << PowDigSum ( n , x ) ; 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 l = 0 ; int r = len - 1 ; int area = 0 ; while ( l < r ) { area = max ( area , min ( A [ l ] , A [ r ] ) * ( r - l ) ) ; if ( A [ l ] < A [ r ] ) l += 1 ; else r -= 1 ; } 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 Mobius Function | Program to print all prime factors ; Returns value of mobius ( ) ; Handling 2 separately ; If 2 ^ 2 also divides N ; Check for all other prime factors ; If i divides n ; If i ^ 2 also divides N ; Driver code | # include <bits/stdc++.h> NEW_LINE using namespace std ; int mobius ( int n ) { int p = 0 ; if ( n % 2 == 0 ) { n = n / 2 ; p ++ ; if ( n % 2 == 0 ) return 0 ; } for ( int i = 3 ; i <= sqrt ( n ) ; i = i + 2 ) { if ( n % i == 0 ) { n = n / i ; p ++ ; if ( n % i == 0 ) return 0 ; } } return ( p % 2 == 0 ) ? -1 : 1 ; } int main ( ) { int N = 17 ; cout << " Mobius β Functions β M ( N ) β at β N β = β " << N << " β is : β " << mobius ( N ) << endl ; cout << " Mobius β Functions β M ( N ) β at β N β = β " << 25 << " β is : β " << mobius ( 25 ) << endl ; cout << " Mobius β Functions β M ( N ) β at β N β = β " << 6 << " β is : β " << mobius ( 6 ) << endl ; } |
Sum of squares of binomial coefficients | CPP Program to find the sum of square of binomial coefficient . ; function to return product of number from start to end . ; Return the sum of square of binomial coefficient ; Driven Program | #include <bits/stdc++.h> NEW_LINE using namespace std ; int factorial ( int start , int end ) { int res = 1 ; for ( int i = start ; i <= end ; i ++ ) res *= i ; return res ; } int sumofsquare ( int n ) { return factorial ( n + 1 , 2 * n ) / factorial ( 1 , n ) ; } int main ( ) { int n = 4 ; cout << sumofsquare ( n ) << endl ; return 0 ; } |
Find nth Fibonacci number using Golden ratio | CPP program to find n - th Fibonacci number ; Approximate value of golden ratio ; Fibonacci numbers upto n = 5 ; Function to find nth Fibonacci number ; Fibonacci numbers for n < 6 ; Else start counting from 5 th term ; driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; double PHI = 1.6180339 ; int f [ 6 ] = { 0 , 1 , 1 , 2 , 3 , 5 } ; int fib ( int n ) { if ( n < 6 ) return f [ n ] ; int t = 5 , fn = 5 ; while ( t < n ) { fn = round ( fn * PHI ) ; t ++ ; } return fn ; } int main ( ) { int n = 9 ; cout << n << " th β Fibonacci β Number β = β " << fib ( n ) << endl ; return 0 ; } |
Euler Method for solving differential equation | CPP Program to find approximation of a ordinary differential equation using euler method . ; Consider a differential equation dy / dx = ( x + y + xy ) ; Function for Euler formula ; Iterating till the point at which we need approximation ; Printing approximation ; Driver program ; Initial Values ; Value of x at which we need approximation | #include <iostream> NEW_LINE using namespace std ; float func ( float x , float y ) { return ( x + y + x * y ) ; } void euler ( float x0 , float y , float h , float x ) { float temp = -0 ; while ( x0 < x ) { temp = y ; y = y + h * func ( x0 , y ) ; x0 = x0 + h ; } cout << " Approximate β solution β at β x β = β " << x << " β is β " << y << endl ; } int main ( ) { float x0 = 0 ; float y0 = 1 ; float h = 0.025 ; float x = 0.1 ; euler ( x0 , y0 , h , x ) ; return 0 ; } |
Find x and y satisfying ax + by = n | CPP program to find solution of ax + by = n ; function to find the solution ; traverse for all possible values ; check if it is satisfying the equation ; driver program to test the above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; void solution ( int a , int b , int n ) { for ( int i = 0 ; i * a <= n ; i ++ ) { if ( ( n - ( i * a ) ) % b == 0 ) { cout << " x β = β " << i << " , β y β = β " << ( n - ( i * a ) ) / b ; return ; } } cout << " No β solution " ; } int main ( ) { int a = 2 , b = 3 , n = 7 ; solution ( a , b , n ) ; return 0 ; } |
Sum of Binomial coefficients | CPP Program to find sum of Binomial Coefficient . ; Returns value of Binomial Coefficient Sum which is 2 raised to power n . ; Driver program to test above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; int binomialCoeffSum ( int n ) { return ( 1 << n ) ; } int main ( ) { int n = 4 ; printf ( " % d " , binomialCoeffSum ( n ) ) ; return 0 ; } |
Program to compute division upto n decimal places | CPP program to compute division upto n decimal places . ; Base cases ; Since n <= 0 , don 't compute after the decimal ; Handling negative numbers ; Integral division ; Now one by print digits after dot using school division method . ; Driver Program | #include <bits/stdc++.h> NEW_LINE using namespace std ; void precisionCompute ( int x , int y , int n ) { if ( y == 0 ) { cout << " Infinite " << endl ; return ; } if ( x == 0 ) { cout << 0 << endl ; return ; } if ( n <= 0 ) { cout << x / y << endl ; return ; } if ( ( ( x > 0 ) && ( y < 0 ) ) || ( ( x < 0 ) && ( y > 0 ) ) ) { cout << " - " ; x = x > 0 ? x : - x ; y = y > 0 ? y : - y ; } int d = x / y ; for ( int i = 0 ; i <= n ; i ++ ) { cout << d ; x = x - ( y * d ) ; if ( x == 0 ) break ; x = x * 10 ; d = x / y ; if ( i == 0 ) cout << " . " ; } } int main ( ) { int x = 22 , y = 7 , n = 15 ; precisionCompute ( x , y , n ) ; return 0 ; } |
Program to determine the quadrant of the cartesian plane | CPP program to check quadrant ; Function to check quadrant ; Driver code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void quadrant ( int x , int y ) { if ( x > 0 and y > 0 ) cout << " lies β in β First β quadrant " ; else if ( x < 0 and y > 0 ) cout << " lies β in β Second β quadrant " ; else if ( x < 0 and y < 0 ) cout << " lies β in β Third β quadrant " ; else if ( x > 0 and y < 0 ) cout << " lies β in β Fourth β quadrant " ; else if ( x == 0 and y > 0 ) cout << " lies β at β positive β y β axis " ; else if ( x == 0 and y < 0 ) cout << " lies β at β negative β y β axis " ; else if ( y == 0 and x < 0 ) cout << " lies β at β negative β x β axis " ; else if ( y == 0 and x > 0 ) cout << " lies β at β positive β x β axis " ; else cout << " lies β at β origin " ; } int main ( ) { int x = 1 , y = 1 ; quadrant ( x , y ) ; return 0 ; } |
Check if a number is Full Prime | CPP program for checking of full prime ; function to check digits ; check all digits are prime or not ; check if digits are prime or not ; To check if n is prime or not ; check for all factors ; To check if n is Full Prime ; The order is important here for efficiency . ; Driver code to check the above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkDigits ( int n ) { while ( n ) { int dig = n % 10 ; if ( dig != 2 && dig != 3 && dig != 5 && dig != 7 ) return false ; n /= 10 ; } return true ; } bool prime ( int n ) { if ( n == 1 ) return false ; for ( int i = 2 ; i * i <= n ; i ++ ) { if ( n % i == 0 ) return false ; } return true ; } int isFullPrime ( int n ) { return ( checkDigits ( n ) && prime ( n ) ) ; } int main ( ) { int n = 53 ; if ( isFullPrime ( n ) ) cout << " Yes " ; else cout << " No " ; return 0 ; } |
Narcissistic number | CPP program for checking of Narcissistic number ; Traversing through the string ; Since ascii value of numbers starts from 48 so we subtract it from sum ; Converting string to integer ; Comparing number and sum ; Driver Code | #include <bits/stdc++.h> NEW_LINE #include <string.h> NEW_LINE using namespace std ; string getResult ( string st ) { int sum = 0 ; int length = st . length ( ) ; for ( int i = 0 ; i < length ; i ++ ) { sum = sum + pow ( st [ i ] - '0' , length ) ; } int number = stoi ( st ) ; if ( number == sum ) return " yes " ; else return " no " ; } int main ( ) { string st = "153" ; cout << getResult ( st ) ; return 0 ; } |
SchrΓ ΒΆ derΓ’ β¬β Hipparchus number | A memoization based optimized CPP program to find n - th SchrAderaHipparchus number ; Driven Program | #include <bits/stdc++.h> NEW_LINE #define MAX 500 NEW_LINE using namespace std ; int nthSHN ( int n , int dp [ ] ) { if ( n == 1 n == 2 ) return dp [ n ] = 1 ; if ( dp [ n ] != -1 ) return dp [ n ] ; return dp [ n ] = ( ( 6 * n - 9 ) * nthSHN ( n - 1 , dp ) - ( n - 3 ) * nthSHN ( n - 2 , dp ) ) / n ; } int main ( ) { int n = 6 ; int dp [ MAX ] ; memset ( dp , -1 , sizeof dp ) ; cout << nthSHN ( n , dp ) << endl ; return 0 ; } |
Sum of first n even numbers | C ++ implementation to find sum of first n even numbers ; function to find sum of first n even numbers ; sum of first n even numbers ; next even number ; required sum ; Driver program to test above | #include <bits/stdc++.h> NEW_LINE using namespace std ; int evenSum ( int n ) { int curr = 2 , sum = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { sum += curr ; curr += 2 ; } return sum ; } int main ( ) { int n = 20 ; cout << " Sum β of β first β " << n << " β Even β numbers β is : β " << evenSum ( n ) ; return 0 ; } |
Sum of first n even numbers | C ++ implementation to find sum of first n even numbers ; function to find sum of first n even numbers ; required sum ; Driver program to test above | #include <bits/stdc++.h> NEW_LINE using namespace std ; int evenSum ( int n ) { return ( n * ( n + 1 ) ) ; } int main ( ) { int n = 20 ; cout << " Sum β of β first β " << n << " β Even β numbers β is : β " << evenSum ( n ) ; return 0 ; } |
Program to Convert Km / hr to miles / hr and vice versa | Cpp program for conversion of kmph to mph and vice versa ; Function to convert kmph to mph ; Function to convert mph to kmph ; Driver code to check the above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; double kmphTOmph ( double kmph ) { return 0.6214 * kmph ; } double mphTOkmph ( double mph ) { return mph * 1.60934 ; } int main ( ) { double kmph = 150 ; double mph = 100 ; cout << " the β speed β in β mph β is β " << kmphTOmph ( kmph ) << endl ; cout << " the β speed β in β kmph β is β " << mphTOkmph ( mph ) ; return 0 ; } |
Number of GP ( Geometric Progression ) subsequences of size 3 | C ++ program to count GP subsequences of size 3. ; 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 ; 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 ; 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 ++ ) 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 ; } |
Find element in array that divides all array elements | CPP program to find such number in the array that all array elements are divisible by it ; Returns gcd of two numbers . ; Function to return the desired number if exists ; Find GCD of array ; Check if GCD is present in array ; Driver Function | #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 findNumber ( int arr [ ] , int n ) { int ans = arr [ 0 ] ; for ( int i = 0 ; i < n ; i ++ ) ans = gcd ( ans , arr [ i ] ) ; for ( int i = 0 ; i < n ; i ++ ) if ( arr [ i ] == ans ) return ans ; return -1 ; } int main ( ) { int arr [ ] = { 2 , 2 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findNumber ( arr , n ) << endl ; return 0 ; } |
Special prime numbers | CPP program to check whether there exist at least k or not in range [ 2. . n ] ; Generating all the prime numbers from 2 to n . ; If a prime number is Special prime number , then we increments the value of k . ; If at least k Special prime numbers are present , then we return 1. else we return 0 from outside of the outer loop . ; Driver function | #include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > primes ; void SieveofEratosthenes ( int n ) { bool visited [ n ] ; for ( int i = 2 ; i <= n + 1 ; i ++ ) if ( ! visited [ i ] ) { for ( int j = i * i ; j <= n + 1 ; j += i ) visited [ j ] = true ; primes . push_back ( i ) ; } } bool specialPrimeNumbers ( int n , int k ) { SieveofEratosthenes ( n ) ; int count = 0 ; for ( int i = 0 ; i < primes . size ( ) ; i ++ ) { for ( int j = 0 ; j < i - 1 ; j ++ ) { if ( primes [ j ] + primes [ j + 1 ] + 1 == primes [ i ] ) { count ++ ; break ; } } if ( count == k ) return true ; } return false ; } int main ( ) { int n = 27 , k = 2 ; if ( specialPrimeNumbers ( n , k ) ) cout << " YES " << endl ; else cout << " NO " << endl ; return 0 ; } |
Prime factors of a big number | CPP program to print prime factors and their powers . ; function to calculate all the prime factors and count of every prime factor ; count the number of times 2 divides ; n >>= 1 ; equivalent to n = n / 2 ; ; if 2 divides it ; check for all the possible numbers that can divide it ; if n at the end is a prime number . ; driver program to test the above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; void factorize ( long long n ) { int count = 0 ; while ( ! ( n % 2 ) ) { count ++ ; } if ( count ) cout << 2 << " β " << count << endl ; for ( long long i = 3 ; i <= sqrt ( n ) ; i += 2 ) { count = 0 ; while ( n % i == 0 ) { count ++ ; n = n / i ; } if ( count ) cout << i << " β " << count << endl ; } if ( n > 2 ) cout << n << " β " << 1 << endl ; } int main ( ) { long long n = 1000000000000000000 ; factorize ( n ) ; return 0 ; } |
Minimum gcd operations to make all array elements one | CPP program to find minimum GCD operations to make all array elements one . ; Function to count number of moves . ; Counting Number of ones . ; If there is a one ; Find smallest subarray with GCD equals to one . ; to calculate GCD ; Not Possible ; Final answer ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minimumMoves ( int A [ ] , int N ) { int one = 0 ; for ( int i = 0 ; i < N ; i ++ ) if ( A [ i ] == 1 ) one ++ ; if ( one != 0 ) return N - one ; int minimum = INT_MAX ; for ( int i = 0 ; i < N ; i ++ ) { int g = A [ i ] ; for ( int j = i + 1 ; j < N ; j ++ ) { g = __gcd ( A [ j ] , g ) ; if ( g == 1 ) { minimum = min ( minimum , j - i ) ; break ; } } } if ( minimum == INT_MAX ) return -1 ; else return N + minimum - 1 ; } int main ( ) { int A [ ] = { 2 , 4 , 3 , 9 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << minimumMoves ( A , N ) ; return 0 ; } |
Given N and Standard Deviation , find N elements | CPP program to find n elements ; function to print series of n elements ; if S . D . is 0 then print all elements as 0. ; print n 0 's ; if S . D . is even ; print - SD , + SD , - SD , + SD ; if odd ; convert n to a float integer ; print one element to be 0 ; print ( n - 1 ) elements as xi derived from the formula ; driver program to test the above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; void series ( int n , int d ) { if ( d == 0 ) { for ( int i = 0 ; i < n ; i ++ ) cout << "0 β " ; cout << endl ; return ; } if ( n % 2 == 0 ) { for ( int i = 1 ; i <= n ; i ++ ) { cout << pow ( -1 , i ) * d << " β " ; } cout << endl ; } else { float m = n ; float r = ( m / ( m - 1 ) ) ; float g = ( float ) ( d * ( float ) sqrtf ( r ) ) ; cout << "0 β " ; for ( int i = 1 ; i < n ; i ++ ) { cout << pow ( -1 , i ) * g << " β " ; } cout << endl ; } } int main ( ) { int n = 3 , d = 3 ; series ( n , d ) ; return 0 ; } |
Total no of 1 's in numbers | c ++ code to count the frequency of 1 in numbers less than or equal to the given number . ; driver function | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countDigitOne ( int n ) { int countr = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { string str = to_string ( i ) ; countr += count ( str . begin ( ) , str . end ( ) , '1' ) ; } return countr ; } int main ( ) { int n = 13 ; cout << countDigitOne ( n ) << endl ; n = 131 ; cout << countDigitOne ( n ) << endl ; n = 159 ; cout << countDigitOne ( n ) << endl ; return 0 ; } |
Exponential Squaring ( Fast Modulo Multiplication ) | C ++ program to compute exponential value using ( 2 ^ k ) - ary method . ; # define N 1000000007L ; prime modulo value ; for cases where exponent is not an even value ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; long exponentiation ( long base , long exp ) { long t = 1L ; while ( exp > 0 ) { if ( exp % 2 != 0 ) t = ( t * base ) % N ; base = ( base * base ) % N ; exp /= 2 ; } return t % N ; } int main ( ) { long base = 5 ; long exp = 100000 ; long modulo = exponentiation ( base , exp ) ; cout << ( modulo ) ; return 0 ; } |
GCD of factorials of two numbers | CPP program to find GCD of factorial of two numbers . ; Driver program to test above functions | #include <bits/stdc++.h> NEW_LINE using namespace std ; int factorial ( int x ) { if ( x <= 1 ) return 1 ; int res = 2 ; for ( int i = 3 ; i <= x ; i ++ ) res = res * i ; return res ; } int gcdOfFactorial ( int m , int n ) { return factorial ( min ( m , n ) ) ; } int main ( ) { int m = 5 , n = 9 ; cout << gcdOfFactorial ( m , n ) ; return 0 ; } |
Recursive sum of digits of a number is prime or not | CPP code to check if recursive sum of digits is prime or not . ; Function for recursive digit sum ; function to check if prime or not the single digit ; calls function which returns sum till single digit ; checking prime ; Driver code | #include <iostream> NEW_LINE using namespace std ; int recDigSum ( int n ) { if ( n == 0 ) return 0 ; else { if ( n % 9 == 0 ) return 9 ; else return n % 9 ; } } void check ( int n ) { n = recDigSum ( n ) ; if ( n == 2 or n == 3 or n == 5 or n == 7 ) cout << " Yes " ; else cout << " No " ; } int main ( ) { int n = 5602 ; check ( n ) ; } |
Find n | CPP program to find the value at n - th place in the given sequence ; Definition of findNumber function ; Finding x from equation n = x ( x + 1 ) / 2 + 1 ; Base of current block ; Value of n - th element ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findNumber ( int n ) { int x = ( int ) floor ( ( -1 + sqrt ( 1 + 8 * n - 8 ) ) / 2 ) ; int base = ( x * ( x + 1 ) ) / 2 + 1 ; return n - base + 1 ; } int main ( ) { int n = 55 ; cout << findNumber ( n ) << endl ; return 0 ; } |
Program for weighted mean of natural numbers . | Program to find weighted mean of first n natural numbers using formula . ; Returns weighted mean assuming for numbers { 1 , 2 , . . n } and weights { 1 , 2 , . . n } ; Driver program to test the function . | #include <bits/stdc++.h> NEW_LINE using namespace std ; int weightedMean ( int n ) { return ( 2 * n + 1 ) / 3 ; } int main ( ) { int n = 10 ; cout << weightedMean ( n ) ; return 0 ; } |
Divide every element of one array by other array elements | CPP program to find quotient of array elements ; Function to calculate the quotient of every element of the array ; Calculate the product of all elements ; To calculate the quotient of every array element ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void calculate ( int a [ ] , int b [ ] , int n , int m ) { int mul = 1 ; for ( int i = 0 ; i < m ; i ++ ) if ( b [ i ] != 0 ) mul = mul * b [ i ] ; for ( int i = 0 ; i < n ; i ++ ) { int x = floor ( a [ i ] / mul ) ; cout << x << " β " ; } } int main ( ) { int a [ ] = { 5 , 100 , 8 } ; int b [ ] = { 2 , 3 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; int m = sizeof ( b ) / sizeof ( b [ 0 ] ) ; calculate ( a , b , n , m ) ; return 0 ; } |
Largest power of k in n ! ( factorial ) where k may not be prime | CPP program to find the largest power of k that divides n ! ; To find the power of a prime p in factorial N ; calculating floor ( n / r ) and adding to the count ; increasing the power of p from 1 to 2 to 3 and so on ; returns all the prime factors of k ; vector to store all the prime factors along with their number of occurrence in factorization of k ; Returns largest power of k that divides n ! ; calculating minimum power of all the prime factors of k ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findPowerOfP ( int n , int p ) { int count = 0 ; int r = p ; while ( r <= n ) { count += ( n / r ) ; r = r * p ; } return count ; } vector < pair < int , int > > primeFactorsofK ( int k ) { vector < pair < int , int > > ans ; for ( int i = 2 ; k != 1 ; i ++ ) { if ( k % i == 0 ) { int count = 0 ; while ( k % i == 0 ) { k = k / i ; count ++ ; } ans . push_back ( make_pair ( i , count ) ) ; } } return ans ; } int largestPowerOfK ( int n , int k ) { vector < pair < int , int > > vec ; vec = primeFactorsofK ( k ) ; int ans = INT_MAX ; for ( int i = 0 ; i < vec . size ( ) ; i ++ ) ans = min ( ans , findPowerOfP ( n , vec [ i ] . first ) / vec [ i ] . second ) ; return ans ; } int main ( ) { cout << largestPowerOfK ( 7 , 2 ) << endl ; cout << largestPowerOfK ( 10 , 9 ) << endl ; return 0 ; } |
Minimum number of bombs | CPP program to find number of bombings required to kill all aliens . ; function to print where to shoot ; no . of bombs required ; bomb all the even positions ; bomb all the odd positions ; bomb all the even positions again ; driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; void print ( int n ) { cout << n + n / 2 << endl ; for ( int i = 2 ; i <= n ; i += 2 ) cout << i << " β " ; for ( int i = 1 ; i <= n ; i += 2 ) cout << i << " β " ; for ( int i = 2 ; i <= n ; i += 2 ) cout << i << " β " ; } int main ( ) { int n = 3 ; print ( n ) ; return 0 ; } |
LCM of digits of a given number | CPP program to find LCM of digits of a number ; define lcm function ; If at any point LCM become 0. return it ; driver code | #include <iostream> NEW_LINE #include <boost/math/common_factor.hpp> NEW_LINE using namespace std ; int digitLCM ( int n ) { int lcm = 1 ; while ( n > 0 ) { lcm = boost :: math :: lcm ( n % 10 , lcm ) ; if ( lcm == 0 ) return 0 ; n = n / 10 ; } return lcm ; } int main ( ) { long n = 397 ; cout << digitLCM ( n ) ; return 0 ; } |
Secretary Problem ( A Optimal Stopping Problem ) | C ++ Program to test 1 / e law for Secretary Problem : ; To find closest integer of num . ; Finds best candidate using n / e rule . candidate [ ] represents talents of n candidates . ; Calculating sample size for benchmarking . ; Finding best candidate in sample size ; Finding the first best candidate that is better than benchmark set . ; Driver Code ; n = 8 candidates and candidate array contains talents of n candidate where the largest number means highest talented candidate . ; generating random numbers between 1 to 8 for talent of candidate | #include <iostream> NEW_LINE #include <time.h> NEW_LINE #define e 2.71828 NEW_LINE using namespace std ; int roundNo ( float num ) { return num < 0 ? num - 0.5 : num + 0.5 ; } void printBestCandidate ( int candidate [ ] , int n ) { int sample_size = roundNo ( n / e ) ; cout << " Sample size is " int best = 0 ; for ( int i = 1 ; i < sample_size ; i ++ ) if ( candidate [ i ] > candidate [ best ] ) best = i ; for ( int i = sample_size ; i < n ; i ++ ) if ( candidate [ i ] >= candidate [ best ] ) { best = i ; break ; } if ( best >= sample_size ) cout << endl << " Best β candidate β found β is β " << best + 1 << " β with β talent β " << candidate [ best ] << endl ; else cout << " Couldn ' t β find β a β best β candidate STRNEWLINE " ; } int main ( ) { int n = 8 ; int candidate [ n ] ; srand ( time ( 0 ) ) ; for ( int i = 0 ; i < n ; i ++ ) candidate [ i ] = 1 + rand ( ) % 8 ; cout << " Candidate β : β " ; for ( int i = 0 ; i < n ; i ++ ) cout << i + 1 << " β " ; cout << endl ; cout << " β Talents β : β " ; for ( int i = 0 ; i < n ; i ++ ) cout << candidate [ i ] << " β " ; printBestCandidate ( candidate , n ) ; return 0 ; } |
Newton Forward And Backward Interpolation | CPP Program to interpolate using newton backward interpolation ; Calculation of u mentioned in formula ; Calculating factorial of given n ; Driver code ; number of values given ; y [ ] [ ] is used for difference table and y [ ] [ 0 ] used for input ; Calculating the backward difference table ; Displaying the backward difference table ; Value to interpolate at ; Initializing u and sum | #include <bits/stdc++.h> NEW_LINE using namespace std ; float u_cal ( float u , int n ) { float temp = u ; for ( int i = 1 ; i < n ; i ++ ) temp = temp * ( u + i ) ; return temp ; } int fact ( int n ) { int f = 1 ; for ( int i = 2 ; i <= n ; i ++ ) f *= i ; return f ; } int main ( ) { int n = 5 ; float x [ ] = { 1891 , 1901 , 1911 , 1921 , 1931 } ; float y [ n ] [ n ] ; y [ 0 ] [ 0 ] = 46 ; y [ 1 ] [ 0 ] = 66 ; y [ 2 ] [ 0 ] = 81 ; y [ 3 ] [ 0 ] = 93 ; y [ 4 ] [ 0 ] = 101 ; for ( int i = 1 ; i < n ; i ++ ) { for ( int j = n - 1 ; j >= i ; j -- ) y [ j ] [ i ] = y [ j ] [ i - 1 ] - y [ j - 1 ] [ i - 1 ] ; } for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j <= i ; j ++ ) cout << setw ( 4 ) << y [ i ] [ j ] << " TABSYMBOL " ; cout << endl ; } float value = 1925 ; float sum = y [ n - 1 ] [ 0 ] ; float u = ( value - x [ n - 1 ] ) / ( x [ 1 ] - x [ 0 ] ) ; for ( int i = 1 ; i < n ; i ++ ) { sum = sum + ( u_cal ( u , i ) * y [ n - 1 ] [ i ] ) / fact ( i ) ; } cout << " Value at " β < < β value β < < β " is " << sum << endl ; return 0 ; } |
Happy Numbers | A space optimized CPP program to check if a number is happy number ; Returns sum of squares of digits of a number n . For example for n = 12 it returns 1 + 4 = 5 ; Returns true if n is Happy number else returns false . ; Keep replacing n with sum of squares of digits until we either reach 1 or we end up in a cycle ; Number is Happy if we reach 1 ; Replace n with sum of squares of digits ; Number is not Happy if we reach 4 ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int sumDigitSquare ( int n ) { int sq = 0 ; while ( n ) { int digit = n % 10 ; sq += digit * digit ; n = n / 10 ; } return sq ; } bool isHappy ( int n ) { while ( 1 ) { if ( n == 1 ) return true ; n = sumDigitSquare ( n ) ; if ( n == 4 ) return false ; } return false ; } int main ( ) { int n = 23 ; if ( isHappy ( n ) ) cout << " Yes " << endl ; else cout << " No " << endl ; return 0 ; } |
Sum of all subsets of a set formed by first n natural numbers | CPP program to find sum of all subsets of a set . ; sum of subsets is ( n * ( n + 1 ) / 2 ) * pow ( 2 , n - 1 ) ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; unsigned long long findSumSubsets ( int n ) { return ( n * ( n + 1 ) / 2 ) * ( 1 << ( n - 1 ) ) ; } int main ( ) { int n = 3 ; cout << findSumSubsets ( n ) ; return 0 ; } |
Minimum element whose n | CPP program to find minimum element whose n - th power is greater than product of an array of size n ; function to find the minimum element ; loop to traverse and store the sum of log ; calculates the elements according to formula . ; returns the minimal element ; Driver program to test above function ; initialised array ; computes the size of array ; prints out the minimal element | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findMin ( int a [ ] , int n ) { double sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) int x = exp ( sum / n ) ; return x + 1 ; } int main ( ) { int a [ ] = { 3 , 2 , 1 , 4 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << findMin ( a , n ) ; } |
Generate all cyclic permutations of a number | Program to generate all cyclic permutations of number ; Function to count the total number of digits in a number . ; Function to generate all cyclic permutations of a number ; Following three lines generates a circular pirmutation of a number . ; If all the permutations are checked and we obtain original number exit from loop . ; Driver Program | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countdigits ( int N ) { int count = 0 ; while ( N ) { count ++ ; N = N / 10 ; } return count ; } void cyclic ( int N ) { int num = N ; int n = countdigits ( N ) ; while ( 1 ) { cout << num << endl ; int rem = num % 10 ; int div = num / 10 ; num = ( pow ( 10 , n - 1 ) ) * rem + div ; if ( num == N ) break ; } } int main ( ) { int N = 5674 ; cyclic ( N ) ; return 0 ; } |
Check whether a number is circular prime or not | Program to check if a number is circular prime or not . ; Function to check if a number is prime or not . ; Corner cases ; This is checked so that we can skip middle five numbers in below loop ; Function to check if the number is circular prime or not . ; Count digits . ; Following three lines generate the next circular permutation of a number . We move last digit to first position . ; If all the permutations are checked and we obtain original number exit from loop . ; Driver Program | #include <iostream> NEW_LINE #include <cmath> NEW_LINE using namespace std ; bool isPrime ( int n ) { if ( n <= 1 ) return false ; if ( n <= 3 ) return true ; if ( n % 2 == 0 n % 3 == 0 ) return false ; for ( int i = 5 ; i * i <= n ; i = i + 6 ) if ( n % i == 0 || n % ( i + 2 ) == 0 ) return false ; return true ; } bool checkCircular ( int N ) { int count = 0 , temp = N ; while ( temp ) { count ++ ; temp /= 10 ; } int num = N ; while ( isPrime ( num ) ) { int rem = num % 10 ; int div = num / 10 ; num = ( pow ( 10 , count - 1 ) ) * rem + div ; if ( num == N ) return true ; } return false ; } int main ( ) { int N = 1193 ; if ( checkCircular ( N ) ) cout << " Yes " << endl ; else cout << " No " << endl ; return 0 ; } |
Find if two people ever meet after same number of jumps | C ++ program to find any one of them can overtake the other ; function to find if any one of them can overtake the other ; Since starting points are always different , they will meet if following conditions are met . ( 1 ) Speeds are not same ( 2 ) Difference between speeds divide the total distance between initial points . ; driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool sackRace ( int p1 , int s1 , int p2 , int s2 ) { return ( ( s1 > s2 && ( p2 - p1 ) % ( s1 - s2 ) == 0 ) || ( s2 > s1 && ( p1 - p2 ) % ( s2 - s1 ) == 0 ) ) ; } int main ( ) { int p1 = 4 , s1 = 4 , p2 = 8 , s2 = 2 ; sackRace ( p1 , s1 , p2 , s2 ) ? cout << " Yes STRNEWLINE " : cout << " No STRNEWLINE " ; return 0 ; } |
Largest proper fraction with sum of numerator and denominator equal to a given number | CPP program to find the largest fraction a / b such that a + b is equal to given number and a < b . ; Calculate N / 2 ; ; Check if N is odd or even ; If N is odd answer will be ceil ( n / 2 ) - 1 and floor ( n / 2 ) + 1 ; If N is even check if N / 2 i . e a is even or odd ; If N / 2 is even apply the previous formula ; If N / 2 is odd answer will be ceil ( N / 2 ) - 2 and floor ( N / 2 ) + 2 ; driver function | #include <iostream> NEW_LINE #include <cmath> NEW_LINE using namespace std ; void solve ( int n ) { float a = ( float ) n / 2 ; if ( n % 2 != 0 ) cout << ceil ( a ) - 1 << " β " << floor ( a ) + 1 << endl ; else { if ( ( int ) a % 2 == 0 ) { cout << ceil ( a ) - 1 << " β " << floor ( a ) + 1 << endl ; } else { cout << ceil ( a ) - 2 << " β " << floor ( a ) + 2 << endl ; } } } int main ( ) { int n = 34 ; solve ( n ) ; return 0 ; } |
Program to find simple interest | CPP program to find simple interest for given principal amount , time and rate of interest . ; We can change values here for different inputs ; Calculate simple interest ; Print the resultant value of SI | #include <iostream> NEW_LINE using namespace std ; int main ( ) { float P = 1 , R = 1 , T = 1 ; float SI = ( P * T * R ) / 100 ; cout << " Simple β Interest β = β " << SI ; return 0 ; } |
Number of digits in the product of two numbers | C ++ implementation to count number of digits in the product of two numbers ; function to count number of digits in the product of two numbers ; absolute value of the product of two numbers ; if product is 0 ; count number of digits in the product ' p ' ; required count of digits ; Driver program to test above | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countDigits ( int a , int b ) { int count = 0 ; int p = abs ( a * b ) ; if ( p == 0 ) return 1 ; while ( p > 0 ) { count ++ ; p = p / 10 ; } return count ; } int main ( ) { int a = 33 ; int b = -24 ; cout << " Number β of β digits β = β " << countDigits ( a , b ) ; return 0 ; } |
Find multiple of x closest to or a ^ b ( a raised to power b ) | C ++ Program to find closest multiple of x to a ^ b ; function to find closest multiple of x to a ^ b ; calculate a ^ b / x ; Answer is either ( ans * x ) or ( ans + 1 ) * x ; Printing nearest answer ; Driver Program | #include <bits/stdc++.h> NEW_LINE using namespace std ; void multiple ( int a , int b , int x ) { if ( b < 0 ) { if ( a == 1 && x == 1 ) cout << "1" ; else cout << "0" ; } int mul = pow ( a , b ) ; int ans = mul / x ; int ans1 = x * ans ; int ans2 = x * ( ans + 1 ) ; cout << ( ( ( mul - ans1 ) <= ( ans2 - mul ) ) ? ans1 : ans2 ) ; } int main ( ) { int a = 349 , b = 1 , x = 4 ; multiple ( a , b , x ) ; return 0 ; } |
Maximum sum of difference of adjacent elements | CPP program to find maximum sum of adjacent elements of permutation of n ; To find max sum of permutation ; Base case ; Otherwise max sum will be ( n * ( n - 1 ) / 2 ) - 1 + n / 2 ; Driver program to test maxSum ( ) | #include <iostream> NEW_LINE using namespace std ; int maxSum ( int n ) { if ( n == 1 ) return 1 ; else return ( n * ( n - 1 ) / 2 ) - 1 + n / 2 ; } int main ( ) { int n = 3 ; cout << maxSum ( n ) ; return 0 ; } |
Compute average of two numbers without overflow | C ++ code to compute average of two numbers ; Function to compute average of two numbers ; Driver code ; Assigning maximum integer value ; Average of two equal numbers is the same number ; Function to get the average of 2 numbers | #include <bits/stdc++.h> NEW_LINE using namespace std ; int compute_average ( int a , int b ) { return ( a + b ) / 2 ; } int main ( ) { int a = INT_MAX , b = INT_MAX ; cout << " Actual β average β : β " << INT_MAX << endl ; cout << " Computed β average β : β " << compute_average ( a , b ) ; return 0 ; } |
Add minimum number to an array so that the sum becomes even | CPP program to add minimum number so that the sum of array becomes even ; Function to find out minimum number ; Count odd number of terms in array ; Driver code | #include <iostream> NEW_LINE using namespace std ; int minNum ( int arr [ ] , int n ) { bool odd = 0 ; for ( int i = 0 ; i < n ; i ++ ) if ( arr [ i ] % 2 ) odd = ! odd ; if ( odd ) return 1 ; return 2 ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << minNum ( arr , n ) << " n " ; return 0 ; } |
Check if a number is jumbled or not | CPP code to check if a number is jumbled or not ; Function to check if a number is jumbled or not ; Single digit number ; Checking every digit through a loop ; All digits were checked ; Digit at index i ; Digit at index i - 1 ; If difference is greater than 1 ; Number checked ; Driver code ; - 1234 to be checked ; 287 to be checked | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkJumbled ( int num ) { if ( num / 10 == 0 ) return true ; while ( num != 0 ) { if ( num / 10 == 0 ) return true ; int digit1 = num % 10 ; int digit2 = ( num / 10 ) % 10 ; if ( abs ( digit2 - digit1 ) > 1 ) return false ; num = num / 10 ; } return true ; } int main ( ) { int num = -1234 ; if ( checkJumbled ( num ) ) cout << " True β STRNEWLINE " ; else cout << " False β STRNEWLINE " ; num = -1247 ; if ( checkJumbled ( num ) ) cout << " True β STRNEWLINE " ; else cout << " False β STRNEWLINE " ; return 0 ; } |
Josephus Problem Using Bit Magic | C ++ program for josephus problem ; function to find the position of the Most Significant Bit ; keeps shifting bits to the right until we are left with 0 ; function to return at which place Josephus should sit to avoid being killed ; Getting the position of the Most Significant Bit ( MSB ) . The leftmost '1' . If the number is '41' then its binary is '101001' . So msbPos ( 41 ) = 6 ; ' j ' stores the number with which to XOR the number ' n ' . Since we need '100000' We will do 1 << 6 - 1 to get '100000' ; Toggling the Most Significant Bit . Changing the leftmost '1' to '0' . 101001 ^ 100000 = 001001 ( 9 ) ; Left - shifting once to add an extra '0' to the right end of the binary number 001001 = 010010 ( 18 ) ; Toggling the '0' at the end to '1' which is essentially the same as putting the MSB at the rightmost place . 010010 | 1 = 010011 ( 19 ) ; hard coded driver main function to run the program | #include <bits/stdc++.h> NEW_LINE using namespace std ; int msbPos ( int n ) { int pos = 0 ; while ( n != 0 ) { pos ++ ; n = n >> 1 ; } return pos ; } int josephify ( int n ) { int position = msbPos ( n ) ; int j = 1 << ( position - 1 ) ; n = n ^ j ; n = n << 1 ; n = n | 1 ; return n ; } int main ( ) { int n = 41 ; cout << josephify ( n ) ; return 0 ; |
Count pairs with Odd XOR | C ++ program to count pairs in array whose XOR is odd ; A function will return number of pair whose XOR is odd ; To store count of XOR pair ; If XOR is odd increase count ; Return count ; Driver program to test countXorPair ( ) | #include <iostream> NEW_LINE using namespace std ; int countXorPair ( int arr [ ] , int n ) { int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) if ( ( arr [ i ] ^ arr [ j ] ) % 2 == 1 ) count ++ ; } return count ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countXorPair ( arr , n ) ; return 0 ; } |
Discrete logarithm ( Find an integer k such that a ^ k is congruent modulo b ) | C ++ program to calculate discrete logarithm ; Iterative Function to calculate ( x ^ y ) % p in O ( log y ) ; 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 ; Function to calculate k for given a , b , m ; Store all values of a ^ ( n * i ) of LHS ; Calculate ( a ^ j ) * b and check for collision ; If collision occurs i . e . , LHS = RHS ; Check whether ans lies below m or not ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int powmod ( int x , int y , int p ) { while ( y > 0 ) { if ( y & 1 ) res = ( res * x ) % p ; x = ( x * x ) % p ; } return res ; } int discreteLogarithm ( int a , int b , int m ) { int n = ( int ) sqrt ( m ) + 1 ; unordered_map < int , int > value ; for ( int i = n ; i >= 1 ; -- i ) value [ powmod ( a , i * n , m ) ] = i ; for ( int j = 0 ; j < n ; ++ j ) { int cur = ( powmod ( a , j , m ) * b ) % m ; if ( value [ cur ] ) { int ans = value [ cur ] * n - j ; if ( ans < m ) return ans ; } } return -1 ; } int main ( ) { int a = 2 , b = 3 , m = 5 ; cout << discreteLogarithm ( a , b , m ) << endl ; a = 3 , b = 7 , m = 11 ; cout << discreteLogarithm ( a , b , m ) ; } |
Discrete logarithm ( Find an integer k such that a ^ k is congruent modulo b ) | C ++ program to calculate discrete logarithm ; Calculate a ^ n ; Store all values of a ^ ( n * i ) of LHS ; Calculate ( a ^ j ) * b and check for collision ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int discreteLogarithm ( int a , int b , int m ) { int n = ( int ) sqrt ( m ) + 1 ; int an = 1 ; for ( int i = 0 ; i < n ; ++ i ) an = ( an * a ) % m ; unordered_map < int , int > value ; for ( int i = 1 , cur = an ; i <= n ; ++ i ) { if ( ! value [ cur ] ) value [ cur ] = i ; cur = ( cur * an ) % m ; } for ( int i = 0 , cur = b ; i <= n ; ++ i ) { if ( value [ cur ] ) { int ans = value [ cur ] * n - i ; if ( ans < m ) return ans ; } cur = ( cur * a ) % m ; } return -1 ; } int main ( ) { int a = 2 , b = 3 , m = 5 ; cout << discreteLogarithm ( a , b , m ) << endl ; a = 3 , b = 7 , m = 11 ; cout << discreteLogarithm ( a , b , m ) ; } |
Finding n | CPP program to find n - th number with prime digits 2 , 3 and 7 ; remainder for check element position ; if number is 1 st position in tree ; if number is 2 nd position in tree ; if number is 3 rd position in tree ; if number is 4 th position in tree ; Driver code | #include <algorithm> NEW_LINE #include <iostream> NEW_LINE #include <string> NEW_LINE using namespace std ; string nthprimedigitsnumber ( int number ) { int rem ; string num ; while ( number ) { rem = number % 4 ; switch ( rem ) { case 1 : num . push_back ( '2' ) ; break ; case 2 : num . push_back ( '3' ) ; break ; case 3 : num . push_back ( '5' ) ; break ; case 0 : num . push_back ( '7' ) ; break ; } if ( number % 4 == 0 ) number -- ; number = number / 4 ; } reverse ( num . begin ( ) , num . end ( ) ) ; return num ; } int main ( ) { int number = 21 ; cout << nthprimedigitsnumber ( 10 ) << " STRNEWLINE " ; cout << nthprimedigitsnumber ( 21 ) << " STRNEWLINE " ; return 0 ; } |
Count pairs ( a , b ) whose sum of cubes is N ( a ^ 3 + b ^ 3 = N ) | C ++ program to count pairs whose sum cubes is N ; Function to count the pairs satisfying a ^ 3 + b ^ 3 = N ; Check for each number 1 to cbrt ( N ) ; Store cube of a number ; Subtract the cube from given N ; Check if the difference is also a perfect cube ; If yes , then increment count ; Return count ; Driver program ; Loop to Count no . of pairs satisfying a ^ 3 + b ^ 3 = i for N = 1 to 10 | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countPairs ( int N ) { int count = 0 ; for ( int i = 1 ; i <= cbrt ( N ) ; i ++ ) { int cb = i * i * i ; int diff = N - cb ; int cbrtDiff = cbrt ( diff ) ; if ( cbrtDiff * cbrtDiff * cbrtDiff == diff ) count ++ ; } return count ; } int main ( ) { for ( int i = 1 ; i <= 10 ; i ++ ) cout << " For β n β = β " << i << " , β " << countPairs ( i ) << " β pair β exists STRNEWLINE " ; return 0 ; } |
Smallest number S such that N is a factor of S factorial or S ! | Program to find factorial that N belongs to ; Calculate prime factors for a given number ; Container for prime factors ; Iterate from 2 to i ^ 2 finding all factors ; If we still have a remainder it is also a prime factor ; Calculate occurrence of an element in factorial of a number ; Iterate through prime factors ; Check if factorial contains less occurrences of prime factor ; Function to binary search 1 to N ; Prime factors are not in the factorial Increase the lowerbound ; We have reached smallest occurrence ; Smaller factorial satisfying requirements may exist , decrease upperbound ; Calculate prime factors and search ; Driver function | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define ull unsigned long long NEW_LINE map < ull , int > primeFactors ( ull num ) { map < ull , int > ans ; for ( ull i = 2 ; i * i <= num ; i ++ ) { while ( num % i == 0 ) { num /= i ; ans [ i ] ++ ; } } if ( num > 1 ) ans [ num ] ++ ; return ans ; } ull legendre ( ull factor , ull num ) { ull count = 0 , fac2 = factor ; while ( num >= factor ) { count += num / factor ; factor *= fac2 ; } return count ; } bool possible ( map < ull , int > & factors , ull num ) { for ( map < ull , int > :: iterator it = factors . begin ( ) ; it != factors . end ( ) ; ++ it ) { if ( legendre ( it -> first , num ) < it -> second ) return false ; } return true ; } ull search ( ull start , ull end , map < ull , int > & factors ) { ull mid = ( start + end ) / 2 ; if ( ! possible ( factors , mid ) ) return search ( mid + 1 , end , factors ) ; if ( start == mid ) return mid ; return search ( start , mid , factors ) ; } ull findFact ( ull num ) { map < ull , int > factors = primeFactors ( num ) ; return search ( 1 , num , factors ) ; } int main ( ) { cout << findFact ( 6 ) << " n " ; cout << findFact ( 997587429953 ) << " n " ; return 0 ; } |
Finding ' k ' such that its modulus with each array element is same | C ++ implementation of finding all k such that arr [ i ] % k is same for each i ; Prints all k such that arr [ i ] % k is same for all i ; sort the numbers ; max difference will be the difference between first and last element of sorted array ; Case when all the array elements are same ; Find all divisors of d and store in a vector v [ ] ; check for each v [ i ] if its modulus with each array element is same or not ; checking for each array element if its modulus with k is equal to k or not ; if check is true print v [ i ] ; Driver function | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printEqualModNumbers ( int arr [ ] , int n ) { sort ( arr , arr + n ) ; int d = arr [ n - 1 ] - arr [ 0 ] ; if ( d == 0 ) { cout << " Infinite β solution " ; return ; } vector < int > v ; for ( int i = 1 ; i * i <= d ; i ++ ) { if ( d % i == 0 ) { v . push_back ( i ) ; if ( i != d / i ) v . push_back ( d / i ) ; } } for ( int i = 0 ; i < v . size ( ) ; i ++ ) { int temp = arr [ 0 ] % v [ i ] ; int j ; for ( j = 1 ; j < n ; j ++ ) if ( arr [ j ] % v [ i ] != temp ) break ; if ( j == n ) cout << v [ i ] << " β " ; } } int main ( ) { int arr [ ] = { 38 , 6 , 34 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printEqualModNumbers ( arr , n ) ; return 0 ; } |
First digit in product of an array of numbers | C ++ implementation of finding first digit of product of n numbers ; returns the first digit of product of elements of arr [ ] ; stores the logarithm of product of elements of arr [ ] ; fractional ( s ) = s - floor ( s ) ; ans = 10 ^ fract_s ; Driver function | #include <bits/stdc++.h> NEW_LINE using namespace std ; int FirstDigit ( int arr [ ] , int n ) { double S = 0 ; for ( int i = 0 ; i < n ; i ++ ) S = S + log10 ( arr [ i ] * 1.0 ) ; double fract_S = S - floor ( S ) ; int ans = pow ( 10 , fract_S ) ; return ans ; } int main ( ) { int arr [ ] = { 5 , 8 , 3 , 7 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << FirstDigit ( arr , n ) << endl ; return 0 ; } |
Find count of digits in a number that divide the number | C ++ program to count number of digits that divides the number . ; Return the number of digits that divides the number . ; Fetching each digit of the number ; Checking if digit is greater than 0 and can divides n . ; Driven Program | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countDigit ( int n ) { int temp = n , count = 0 ; while ( temp != 0 ) { int d = temp % 10 ; temp /= 10 ; if ( d > 0 && n % d == 0 ) count ++ ; } return count ; } int main ( ) { int n = 1012 ; cout << countDigit ( n ) << endl ; return 0 ; } |
Minimum positive integer to divide a number such that the result is an odd | C ++ program to make a number odd ; Function to find the value ; Return 1 if already odd ; Check how many times it is divided by 2 ; Driver code | #include <iostream> NEW_LINE using namespace std ; int makeOdd ( int n ) { if ( n % 2 != 0 ) return 1 ; int resul = 1 ; while ( n % 2 == 0 ) { n /= 2 ; resul *= 2 ; } return resul ; } int main ( ) { int n = 36 ; cout << makeOdd ( n ) ; return 0 ; } |
Multiple of x closest to n | CPP program to calculate the smallest multiple of x closest to a given number ; Function to calculate the smallest multiple ; driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; int closestMultiple ( int n , int x ) { if ( x > n ) return x ; n = n + x / 2 ; n = n - ( n % x ) ; return n ; } int main ( ) { int n = 9 , x = 4 ; printf ( " % d " , closestMultiple ( n , x ) ) ; return 0 ; } |
Perfect cubes in a range | Efficient method to print cubes between a and b ; An efficient solution to print perfect cubes between a and b ; Find cube root of both a and b ; Print cubes between acrt and bcrt ; Driver code | #include <cmath> NEW_LINE #include <iostream> NEW_LINE using namespace std ; void printCubes ( int a , int b ) { int acrt = cbrt ( a ) ; int bcrt = cbrt ( b ) ; for ( int i = acrt ; i <= bcrt ; i ++ ) if ( i * i * i >= a && i * i * i <= b ) cout << i * i * i << " β " ; } int main ( ) { int a = 24 , b = 576 ; cout << " Perfect β cubes β in β given β range : STRNEWLINE " << printCubes ( a , b ) ; return 0 ; } |
Number of occurrences of 2 as a digit in numbers from 0 to n | C ++ program to count 2 s from 0 to n ; Counts the number of '2' digits in a single number ; Counts the number of '2' digits between 0 and n ; Initialize result ; Count 2 's in every number from 2 to n ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int number0f2s ( int n ) { int count = 0 ; while ( n > 0 ) { if ( n % 10 == 2 ) count ++ ; n = n / 10 ; } return count ; } int numberOf2sinRange ( int n ) { int count = 0 ; for ( int i = 2 ; i <= n ; i ++ ) count += number0f2s ( i ) ; return count ; } int main ( ) { cout << numberOf2sinRange ( 22 ) ; cout << endl ; cout << numberOf2sinRange ( 100 ) ; return 0 ; } |
Minimum toggles to partition a binary array so that it has first 0 s then 1 s | C ++ program to find minimum toggle required ; Function to calculate minimum toggling required by using Dynamic programming ; Fill entries in zero [ ] such that zero [ i ] stores count of zeroes to the left of i ( exl ; If zero found update zero [ ] array ; Finding the minimum toggle required from every index ( 0 to n - 1 ) ; Driver Program | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minToggle ( int arr [ ] , int n ) { int zero [ n + 1 ] ; zero [ 0 ] = 0 ; for ( int i = 1 ; i <= n ; ++ i ) { if ( arr [ i - 1 ] == 0 ) zero [ i ] = zero [ i - 1 ] + 1 ; else zero [ i ] = zero [ i - 1 ] ; } int ans = n ; for ( int i = 1 ; i <= n ; ++ i ) ans = min ( ans , i - zero [ i ] + zero [ n ] - zero [ i ] ) ; return ans ; } int main ( ) { int arr [ ] = { 1 , 0 , 1 , 1 , 0 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << minToggle ( arr , n ) << " STRNEWLINE " ; return 0 ; } |
Check if a large number is divisible by 6 or not | C ++ program to find if a number is divisible by 6 or not ; Function to find that number divisible by 6 or not ; Return false if number is not divisible by 2. ; Compute sum of digits ; Check if sum of digits is divisible by 3 ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool check ( string str ) { int n = str . length ( ) ; if ( ( str [ n - 1 ] - '0' ) % 2 != 0 ) return false ; int digitSum = 0 ; for ( int i = 0 ; i < n ; i ++ ) digitSum += ( str [ i ] - '0' ) ; return ( digitSum % 3 == 0 ) ; } int main ( ) { string str = "1332" ; check ( str ) ? cout << " Yes " : cout << " No β " ; return 0 ; } |
Find ways an Integer can be expressed as sum of n | C ++ program to find number of ways to express a number as sum of n - th powers of numbers . ; Wrapper over checkRecursive ( ) ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int res = 0 ; int checkRecursive ( int num , int x , int k , int n ) { if ( x == 0 ) res ++ ; int r = ( int ) floor ( pow ( num , 1.0 / n ) ) ; for ( int i = k + 1 ; i <= r ; i ++ ) { int a = x - ( int ) pow ( i , n ) ; if ( a >= 0 ) checkRecursive ( num , x - ( int ) pow ( i , n ) , i , n ) ; } return res ; } int check ( int x , int n ) { return checkRecursive ( x , x , 0 , n ) ; } int main ( ) { cout << ( check ( 10 , 2 ) ) ; return 0 ; } |
N 'th palindrome of K digits | A naive approach of C ++ program of finding nth palindrome of k digit ; Utility function to reverse the number n ; Boolean Function to check for palindromic number ; Function for finding nth palindrome of k digits ; Get the smallest k digit number ; check the number is palindrom or not ; if n 'th palindrome found break the loop ; Increment number for checking next palindrome ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int reverseNum ( int n ) { int rem , rev = 0 ; while ( n ) { rem = n % 10 ; rev = rev * 10 + rem ; n /= 10 ; } return rev ; } bool isPalindrom ( int num ) { return num == reverseNum ( num ) ; } int nthPalindrome ( int n , int k ) { int num = ( int ) pow ( 10 , k - 1 ) ; while ( true ) { if ( isPalindrom ( num ) ) -- n ; if ( ! n ) break ; ++ num ; } return num ; } int main ( ) { int n = 6 , k = 5 ; printf ( " % dth β palindrome β of β % d β digit β = β % d STRNEWLINE " , n , k , nthPalindrome ( n , k ) ) ; n = 10 , k = 6 ; printf ( " % dth β palindrome β of β % d β digit β = β % d " , n , k , nthPalindrome ( n , k ) ) ; return 0 ; } |
N 'th palindrome of K digits | C ++ program of finding nth palindrome of k digit ; Determine the first half digits ; Print the first half digits of palindrome ; If k is odd , truncate the last digit ; print the last half digits of palindrome ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void nthPalindrome ( int n , int k ) { int temp = ( k & 1 ) ? ( k / 2 ) : ( k / 2 - 1 ) ; int palindrome = ( int ) pow ( 10 , temp ) ; palindrome += n - 1 ; printf ( " % d " , palindrome ) ; if ( k & 1 ) palindrome /= 10 ; while ( palindrome ) { printf ( " % d " , palindrome % 10 ) ; palindrome /= 10 ; } printf ( " STRNEWLINE " ) ; } int main ( ) { int n = 6 , k = 5 ; printf ( " % dth β palindrome β of β % d β digit β = β " , n , k ) ; nthPalindrome ( n , k ) ; n = 10 , k = 6 ; printf ( " % dth β palindrome β of β % d β digit β = β " , n , k ) ; nthPalindrome ( n , k ) ; return 0 ; } |
Maximum value in an array after m range increment operations | C ++ implementation of simple approach to find maximum value after m range increments . ; Function to find the maximum element after m operations ; start performing m operations ; Store lower and upper index i . e . range ; Add ' k [ i ] ' value at this operation to whole range ; Find maximum value after all operations and return ; Driver code ; Number of values ; value of k to be added at each operation | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findMax ( int n , int a [ ] , int b [ ] , int k [ ] , int m ) { int arr [ n ] ; memset ( arr , 0 , sizeof ( arr ) ) ; for ( int i = 0 ; i < m ; i ++ ) { int lowerbound = a [ i ] ; int upperbound = b [ i ] ; for ( int j = lowerbound ; j <= upperbound ; j ++ ) arr [ j ] += k [ i ] ; } int res = INT_MIN ; for ( int i = 0 ; i < n ; i ++ ) res = max ( res , arr [ i ] ) ; return res ; } int main ( ) { int n = 5 ; int a [ ] = { 0 , 1 , 2 } ; int b [ ] = { 1 , 4 , 3 } ; int k [ ] = { 100 , 100 , 100 } ; int m = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << " Maximum β value β after β ' m ' β operations β is β " << findMax ( n , a , b , k , m ) ; return 0 ; } |
Summation of GCD of all the pairs up to N | C ++ approach of finding sum of GCD of all pairs ; phi [ i ] stores euler totient function for i result [ j ] stores result for value j ; Precomputation of phi [ ] numbers . Refer below link for details : https : goo . gl / LUqdtY ; Refer https : goo . gl / LUqdtY ; Precomputes result for all numbers till MAX ; Precompute all phi value ; Iterate throght all the divisors of i . ; Add summation of previous calculated sum ; Driver code ; Function to calculate sum of all the GCD pairs | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 100001 NEW_LINE long long phi [ MAX ] , result [ MAX ] ; void computeTotient ( ) { phi [ 1 ] = 1 ; for ( int i = 2 ; i < MAX ; i ++ ) { if ( ! phi [ i ] ) { phi [ i ] = i - 1 ; for ( int j = ( i << 1 ) ; j < MAX ; j += i ) { if ( ! phi [ j ] ) phi [ j ] = j ; phi [ j ] = ( phi [ j ] / i ) * ( i - 1 ) ; } } } } void sumOfGcdPairs ( ) { computeTotient ( ) ; for ( int i = 1 ; i < MAX ; ++ i ) { for ( int j = 2 ; i * j < MAX ; ++ j ) result [ i * j ] += i * phi [ j ] ; } for ( int i = 2 ; i < MAX ; i ++ ) result [ i ] += result [ i - 1 ] ; } int main ( ) { sumOfGcdPairs ( ) ; int N = 4 ; cout << " Summation β of β " << N << " β = β " << result [ N ] << endl ; ; N = 12 ; cout << " Summation β of β " << N << " β = β " << result [ N ] << endl ; N = 5000 ; cout << " Summation β of β " << N << " β = β " << result [ N ] ; return 0 ; } |
Find coordinates of the triangle given midpoint of each side | C ++ program to find coordinate of the triangle given midpoint of each side ; Return after solving the equations and finding the vertices coordinate . ; Finding sum of all three coordinate . ; Solving the equation . ; Finds vertices of a triangles from given middle vertices . ; Find X coordinates of vertices . ; Find Y coordinates of vertices . ; Output the solution . ; Driver code | #include <bits/stdc++.h> NEW_LINE #define N 3 NEW_LINE using namespace std ; vector < int > solve ( int v [ ] ) { vector < int > res ; int all3 = v [ 0 ] + v [ 1 ] + v [ 2 ] ; res . push_back ( all3 - v [ 1 ] * 2 ) ; res . push_back ( all3 - v [ 2 ] * 2 ) ; res . push_back ( all3 - v [ 0 ] * 2 ) ; return res ; } void findVertex ( int xmid [ ] , int ymid [ ] ) { vector < int > V1 = solve ( xmid ) ; vector < int > V2 = solve ( ymid ) ; for ( int i = 0 ; i < 3 ; i ++ ) cout << V1 [ i ] << " β " << V2 [ i ] << endl ; } int main ( ) { int xmid [ N ] = { 5 , 4 , 5 } ; int ymid [ N ] = { 3 , 4 , 5 } ; findVertex ( xmid , ymid ) ; return 0 ; } |
N | C ++ program to find n - th number in the sorted list of multiples of two numbers . ; Return the n - th number in the sorted list of multiples of two numbers . ; Generating first n multiple of a . ; Sorting the sequence . ; Generating and storing first n multiple of b and storing if not present in the sequence . ; If not present in the sequence ; Storing in the sequence . ; Driven Program | #include <bits/stdc++.h> NEW_LINE using namespace std ; int nthElement ( int a , int b , int n ) { vector < int > seq ; for ( int i = 1 ; i <= n ; i ++ ) seq . push_back ( a * i ) ; sort ( seq . begin ( ) , seq . end ( ) ) ; for ( int i = 1 , k = n ; i <= n && k ; i ++ ) { if ( ! binary_search ( seq . begin ( ) , seq . end ( ) , b * i ) ) { seq . push_back ( b * i ) ; sort ( seq . begin ( ) , seq . end ( ) ) ; k -- ; } } return seq [ n - 1 ] ; } int main ( ) { int a = 3 , b = 5 , n = 5 ; cout << nthElement ( a , b , n ) << endl ; return 0 ; } |
Count pairs of natural numbers with GCD equal to given number | C ++ program to count pair in range of natural number having GCD equal to given number . ; Return the GCD of two numbers . ; Return the count of pairs having GCD equal to g . ; Setting the value of L , R . ; For each possible pair check if GCD is 1. ; Driven Program | #include <bits/stdc++.h> NEW_LINE using namespace std ; int gcd ( int a , int b ) { return b ? gcd ( b , a % b ) : a ; } int countGCD ( int L , int R , int g ) { L = ( L + g - 1 ) / g ; R = R / g ; int ans = 0 ; for ( int i = L ; i <= R ; i ++ ) for ( int j = L ; j <= R ; j ++ ) if ( gcd ( i , j ) == 1 ) ans ++ ; return ans ; } int main ( ) { int L = 1 , R = 11 , g = 5 ; cout << countGCD ( L , R , g ) << endl ; return 0 ; } |
Last non | C ++ program to find last non - zero digit in n ! ; Initialize values of last non - zero digit of numbers from 0 to 9 ; Check whether tens ( or second last ) digit is odd or even If n = 375 , So n / 10 = 37 and ( n / 10 ) % 10 = 7 Applying formula for even and odd cases . ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int dig [ ] = { 1 , 1 , 2 , 6 , 4 , 2 , 2 , 4 , 2 , 8 } ; int lastNon0Digit ( int n ) { if ( n < 10 ) return dig [ n ] ; if ( ( ( n / 10 ) % 10 ) % 2 == 0 ) return ( 6 * lastNon0Digit ( n / 5 ) * dig [ n % 10 ] ) % 10 ; else return ( 4 * lastNon0Digit ( n / 5 ) * dig [ n % 10 ] ) % 10 ; } int main ( ) { int n = 14 ; cout << lastNon0Digit ( n ) ; return 0 ; } |
Find the first natural number whose factorial is divisible by x | C ++ program to find first natural number whose factorial divides x . ; GCD function to compute the greatest divisor among a and b ; Returns first number whose factorial divides x . ; int i = 1 ; Result ; Remove common factors ; We found first i . ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int gcd ( int a , int b ) { if ( ( a % b ) == 0 ) return b ; return gcd ( b , a % b ) ; } int firstFactorialDivisibleNumber ( int x ) { int new_x = x ; for ( i = 1 ; i < x ; i ++ ) { new_x /= gcd ( i , new_x ) ; if ( new_x == 1 ) break ; } return i ; } int main ( void ) { int x = 16 ; cout << firstFactorialDivisibleNumber ( x ) ; return 0 ; } |
Find the highest occurring digit in prime numbers in a range | C ++ program to find the highest occurring digit in prime numbers in a range L to R . ; Sieve of Eratosthenes ; Returns maximum occurring digits in primes from l to r . ; Finding the prime number up to R . ; Initialise frequency of all digit to 0. ; For all number between L to R , check if prime or not . If prime , incrementing the frequency of digits present in the prime number . ; int p = i ; If i is prime ; Finding digit with highest frequency . ; Driven Program | #include <bits/stdc++.h> NEW_LINE using namespace std ; void sieve ( bool prime [ ] , int n ) { prime [ 0 ] = prime [ 1 ] = true ; for ( int p = 2 ; p * p <= n ; p ++ ) { if ( prime [ p ] == false ) for ( int i = p * 2 ; i <= n ; i += p ) prime [ i ] = true ; } } int maxDigitInPrimes ( int L , int R ) { bool prime [ R + 1 ] ; memset ( prime , 0 , sizeof ( prime ) ) ; sieve ( prime , R ) ; int freq [ 10 ] = { 0 } ; int val ; for ( int i = L ; i <= R ; i ++ ) { if ( ! prime [ i ] ) { while ( p ) { freq [ p % 10 ] ++ ; p /= 10 ; } } } int max = freq [ 0 ] , ans = 0 ; for ( int j = 1 ; j < 10 ; j ++ ) { if ( max <= freq [ j ] ) { max = freq [ j ] ; ans = j ; } } return ( max != 0 ) ? ans : -1 ; } int main ( ) { int L = 1 , R = 20 ; cout << maxDigitInPrimes ( L , R ) << endl ; return 0 ; } |
Sphenic Number | C ++ program to check whether a number is a Sphenic number or not ; create a global array of size 10001 ; ; This functions finds all primes smaller than ' limit ' using simple sieve of eratosthenes . ; 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 ; to store the 8 divisors ; to count the number of divisor ; finally check if there re 8 divisor and all the numbers are distinct prime no return 1 else return 0 ; Driver program to test above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool arr [ 1001 ] ; void simpleSieve ( ) { memset ( arr , true , sizeof ( arr ) ) ; for ( int p = 2 ; p * p < 1001 ; p ++ ) { if ( arr [ p ] ) { for ( int i = p * 2 ; i < 1001 ; i = i + p ) arr [ i ] = false ; } } } int find_sphene ( int N ) { int arr1 [ 8 ] = { 0 } ; int count = 0 ; int j = 0 ; for ( int i = 1 ; i <= N ; i ++ ) { if ( N % i == 0 && count < 9 ) { count ++ ; arr1 [ j ++ ] = i ; } } if ( count == 8 && ( arr [ arr1 [ 1 ] ] && arr [ arr1 [ 2 ] ] && arr [ arr1 [ 3 ] ] ) ) return 1 ; return 0 ; } int main ( ) { int n = 60 ; simpleSieve ( ) ; int ans = find_sphene ( n ) ; if ( ans ) cout << " Yes " ; else cout << " NO " ; } |