text
stringlengths 17
4.49k
| code
stringlengths 49
5.46k
|
---|---|
Print the balanced bracket expression using given brackets | C ++ implementation of the approach ; Function to print balanced bracket expression if it is possible ; If the condition is met ; Print brackets of type - 1 ; Print brackets of type - 3 ; Print brackets of type - 4 ; Print brackets of type - 2 ; If the condition is not met ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printBalancedExpression ( int a , int b , int c , int d ) { if ( ( a == d && a ) || ( a == 0 && c == 0 && d == 0 ) ) { for ( int i = 1 ; i <= a ; i ++ ) cout << " ( ( " ; for ( int i = 1 ; i <= c ; i ++ ) cout << " ) ( " ; for ( int i = 1 ; i <= d ; i ++ ) cout << " ) ) " ; for ( int i = 1 ; i <= b ; i ++ ) cout << " ( ) " ; } else cout << -1 ; } int main ( ) { int a = 3 , b = 1 , c = 4 , d = 3 ; printBalancedExpression ( a , b , c , d ) ; return 0 ; } |
Count numbers having N 0 ' s β and β and β M β 1' s with no leading zeros | C ++ implementation of the approach ; Function to return the factorial of a number ; Function to return the count of distinct ( N + M ) digit numbers having N 0 ' s β and β and β M β 1' s with no leading zeros ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define ll long long int NEW_LINE ll factorial ( int f ) { ll fact = 1 ; for ( int i = 2 ; i <= f ; i ++ ) fact *= ( ll ) i ; return fact ; } ll findPermutation ( int N , int M ) { ll permutation = factorial ( N + M - 1 ) / ( factorial ( N ) * factorial ( M - 1 ) ) ; return permutation ; } int main ( ) { int N = 3 , M = 3 ; cout << findPermutation ( N , M ) ; return 0 ; } |
Maximum value of | arr [ 0 ] | C ++ implementation of the approach ; Function to return the maximum required value ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxValue ( int n ) { if ( n == 1 ) return 0 ; return ( ( n * n / 2 ) - 1 ) ; } int main ( ) { int n = 4 ; cout << maxValue ( n ) ; return 0 ; } |
Count of a , b & c after n seconds for given reproduction rate | C ++ implementation of the approach ; Function to print the count of a , b and c after n seconds ; Number of multiples of 60 below n ; Multiple of 60 nearest to n ; Change all a to b ; Change all b to c ; Change each c to two a ; Print the updated values of a , b and c ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define ull unsigned long long NEW_LINE void findCount ( int n ) { ull a = 1 , b = 0 , c = 0 ; int x = n / 60 ; a = ( ull ) pow ( 32 , x ) ; x = 60 * x ; for ( int i = x + 1 ; i <= n ; i ++ ) { if ( i % 2 == 0 ) { b += a ; a = 0 ; } if ( i % 5 == 0 ) { c += b ; b = 0 ; } if ( i % 12 == 0 ) { a += ( 2 * c ) ; c = 0 ; } } cout << " a β = β " << a << " , β " ; cout << " b β = β " << b << " , β " ; cout << " c β = β " << c ; } int main ( ) { int n = 72 ; findCount ( n ) ; return 0 ; } |
Find GCD of factorial of elements of given array | C ++ implementation of the above approach ; Implementation of factorial function ; Function to find GCD of factorial of elements from array ; find the minimum element of array ; return the factorial of minimum element ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int factorial ( int n ) { return ( n == 1 n == 0 ) ? 1 : factorial ( n - 1 ) * n ; } int gcdOfFactorial ( int arr [ ] , int n ) { int minm = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) minm = minm > arr [ i ] ? arr [ i ] : minm ; return factorial ( minm ) ; } int main ( ) { int arr [ ] = { 9 , 12 , 122 , 34 , 15 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << gcdOfFactorial ( arr , n ) ; return 0 ; } |
Sum of the series 1 ^ 1 + 2 ^ 2 + 3 ^ 3 + ... . . + n ^ n using recursion | C ++ implementation of the approach ; Recursive function to return the sum of the given series ; 1 ^ 1 = 1 ; Recursive call ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define ll long long int NEW_LINE ll sum ( int n ) { if ( n == 1 ) return 1 ; else return ( ( ll ) pow ( n , n ) + sum ( n - 1 ) ) ; } int main ( ) { int n = 2 ; cout << sum ( n ) ; return 0 ; } |
Count permutations that are first decreasing then increasing . | C ++ implementation of the above approach ; Function to compute a ^ n % mod ; Function to count permutations that are first decreasing and then increasing ; For n = 1 return 0 ; Calculate and return result ; Driver code | #include <bits/stdc++.h> NEW_LINE #define ll long long NEW_LINE using namespace std ; const int mod = 1000000007 ; ll power ( ll a , ll n ) { if ( n == 0 ) return 1 ; ll p = power ( a , n / 2 ) % mod ; p = ( p * p ) % mod ; if ( n & 1 ) p = ( p * a ) % mod ; return p ; } int countPermutations ( int n ) { if ( n == 1 ) { return 0 ; } return ( power ( 2 , n - 1 ) - 2 ) % mod ; } int main ( ) { int n = 5 ; cout << countPermutations ( n ) ; return 0 ; } |
Find the count of numbers that can be formed using digits 3 , 4 only and having length at max N . | Cpp program to find the count of numbers that can be formed using digits 3 , 4 only and having length at max N . ; Function to find the count of numbers that can be formed using digits 3 , 4 only and having length at max N . ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; long long numbers ( int n ) { return ( long long ) ( pow ( 2 , n + 1 ) ) - 2 ; } int main ( ) { int n = 2 ; cout << numbers ( n ) ; return 0 ; } |
Ways to place 4 items in n ^ 2 positions such that no row / column contains more than one | C ++ implementation of the approach ; Function to return the number of ways to place 4 items in n ^ 2 positions ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; long long NumberofWays ( int n ) { long long x = ( 1LL * ( n ) * ( n - 1 ) * ( n - 2 ) * ( n - 3 ) ) / ( 4 * 3 * 2 * 1 ) ; long long y = ( 1LL * ( n ) * ( n - 1 ) * ( n - 2 ) * ( n - 3 ) ) ; return ( 1LL * x * y ) ; } int main ( ) { int n = 4 ; cout << NumberofWays ( n ) ; return 0 ; } |
Find Nth term of the series 1 , 6 , 18 , 40 , 75 , ... . | CPP code to generate ' Nth ' term of this sequence ; Function to generate a fixed number ; ( N ^ 2 * ( N + 1 ) ) / 2 ; Driver Method | #include <bits/stdc++.h> NEW_LINE using namespace std ; int nthTerm ( int N ) { int nth = 0 ; nth = ( N * N * ( N + 1 ) ) / 2 ; return nth ; } int main ( ) { int N = 5 ; cout << nthTerm ( N ) << endl ; return 0 ; } |
Print n numbers such that their sum is a perfect square | C ++ implementation of the approach ; Function to print n numbers such that their sum is a perfect square ; Print ith odd number ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findNumbers ( int n ) { int i = 1 ; while ( i <= n ) { cout << ( ( 2 * i ) - 1 ) << " β " ; i ++ ; } } int main ( ) { int n = 3 ; findNumbers ( n ) ; } |
Missing even and odd elements from the given arrays | C ++ implementation of the approach ; Function to find the missing numbers ; To store the minimum and the maximum odd and even elements from the arrays ; To store the sum of the array elements ; Get the minimum and the maximum even elements from the array ; Get the minimum and the maximum odd elements from the array ; To store the total terms in the series and the required sum of the array ; Total terms from 2 to minEven ; Sum of all even numbers from 2 to minEven ; Total terms from 2 to maxEven ; Sum of all even numbers from 2 to maxEven ; Required sum for the even array ; Missing even number ; Total terms from 1 to minOdd ; Sum of all odd numbers from 1 to minOdd ; Total terms from 1 to maxOdd ; Sum of all odd numbers from 1 to maxOdd ; Required sum for the odd array ; Missing odd number ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findMissingNums ( int even [ ] , int sizeEven , int odd [ ] , int sizeOdd ) { int minEven = INT_MAX ; int maxEven = INT_MIN ; int minOdd = INT_MAX ; int maxOdd = INT_MIN ; int sumEvenArr = 0 , sumOddArr = 0 ; for ( int i = 0 ; i < sizeEven ; i ++ ) { minEven = min ( minEven , even [ i ] ) ; maxEven = max ( maxEven , even [ i ] ) ; sumEvenArr += even [ i ] ; } for ( int i = 0 ; i < sizeOdd ; i ++ ) { minOdd = min ( minOdd , odd [ i ] ) ; maxOdd = max ( maxOdd , odd [ i ] ) ; sumOddArr += odd [ i ] ; } int totalTerms = 0 , reqSum = 0 ; totalTerms = minEven / 2 ; int evenSumMin = totalTerms * ( totalTerms + 1 ) ; totalTerms = maxEven / 2 ; int evenSumMax = totalTerms * ( totalTerms + 1 ) ; reqSum = evenSumMax - evenSumMin + minEven ; cout << " Even β = β " << reqSum - sumEvenArr << " STRNEWLINE " ; totalTerms = ( minOdd / 2 ) + 1 ; int oddSumMin = totalTerms * totalTerms ; totalTerms = ( maxOdd / 2 ) + 1 ; int oddSumMax = totalTerms * totalTerms ; reqSum = oddSumMax - oddSumMin + minOdd ; cout << " Odd β = β " << reqSum - sumOddArr ; } int main ( ) { int even [ ] = { 6 , 4 , 8 , 14 , 10 } ; int sizeEven = sizeof ( even ) / sizeof ( even [ 0 ] ) ; int odd [ ] = { 7 , 5 , 3 , 11 , 13 } ; int sizeOdd = sizeof ( odd ) / sizeof ( odd [ 0 ] ) ; findMissingNums ( even , sizeEven , odd , sizeOdd ) ; return 0 ; } |
Minimum matches the team needs to win to qualify | C ++ implementation of the approach ; Function to return the minimum number of matches to win to qualify for next round ; Do a binary search to find ; Find mid element ; Check for condition to qualify for next round ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findMinimum ( int x , int y ) { int low = 0 , high = y ; while ( low <= high ) { int mid = ( low + high ) >> 1 ; if ( ( mid * 2 + ( y - mid ) ) >= x ) high = mid - 1 ; else low = mid + 1 ; } return low ; } int main ( ) { int x = 6 , y = 5 ; cout << findMinimum ( x , y ) ; return 0 ; } |
Check if product of digits of a number at even and odd places is equal | C ++ implementation of the approach ; To store the respective product ; Converting integer to string ; Traversing the string ; Driver code | #include <iostream> NEW_LINE using namespace std ; void getResult ( int n ) { int proOdd = 1 ; int proEven = 1 ; string num = to_string ( n ) ; for ( int i = 0 ; i < num . size ( ) ; i ++ ) if ( i % 2 == 0 ) proOdd = proOdd * ( num [ i ] - '0' ) ; else proEven = proEven * ( num [ i ] - '0' ) ; if ( proOdd == proEven ) cout << " Yes " ; else cout << " No " ; } int main ( ) { int n = 4324 ; getResult ( n ) ; return 0 ; } |
Count of all even numbers in the range [ L , R ] whose sum of digits is divisible by 3 | C ++ implementation of the approach ; Function to return the sum of digits of x ; Function to return the count of required numbers ; If i is divisible by 2 and sum of digits of i is divisible by 3 ; Return the required count ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int sumOfDigits ( int x ) { int sum = 0 ; while ( x != 0 ) { sum += x % 10 ; x = x / 10 ; } return sum ; } int countNumbers ( int l , int r ) { int count = 0 ; for ( int i = l ; i <= r ; i ++ ) { if ( i % 2 == 0 && sumOfDigits ( i ) % 3 == 0 ) count ++ ; } return count ; } int main ( ) { int l = 1000 , r = 6000 ; cout << countNumbers ( l , r ) ; return 0 ; } |
Sum of minimum element of all subarrays of a sorted array | C ++ implementation of the above approach ; Function to find the sum of minimum of all subarrays ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findMinSum ( int arr [ ] , int n ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) sum += arr [ i ] * ( n - i ) ; return sum ; } int main ( ) { int arr [ ] = { 3 , 5 , 7 , 8 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findMinSum ( arr , n ) ; return 0 ; } |
Longest Sub | C ++ implementation of the approach ; Function to return the max length of the sub - array that have the maximum average ( average value of the elements ) ; Finding the maximum value ; If consecutive maximum found ; Find the max length of consecutive max ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxLenSubArr ( int a [ ] , int n ) { int count , j ; int cm = 1 , max = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] > max ) max = a [ i ] ; } for ( int i = 0 ; i < n - 1 ; ) { count = 1 ; if ( a [ i ] == a [ i + 1 ] && a [ i ] == max ) { for ( j = i + 1 ; j < n ; j ++ ) { if ( a [ j ] == max ) { count ++ ; i ++ ; } else break ; } if ( count > cm ) cm = count ; } else i ++ ; } return cm ; } int main ( ) { int arr [ ] = { 6 , 1 , 6 , 6 , 0 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maxLenSubArr ( arr , n ) ; return 0 ; } |
Minimum possible sum of array elements after performing the given operation | C ++ implementation of the approach ; Function to return the minimized sum ; To store the largest element from the array which is divisible by x ; Sum of array elements before performing any operation ; If current element is divisible by x and it is maximum so far ; Update the minimum element ; If no element can be reduced then there 's no point in performing the operation as we will end up increasing the sum when an element is multiplied by x ; Subtract the chosen elements from the sum and then add their updated values ; Return the minimized sum ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define ll long long int NEW_LINE ll minSum ( int arr [ ] , int n , int x ) { ll sum = 0 ; int largestDivisible = -1 , minimum = arr [ 0 ] ; for ( int i = 0 ; i < n ; i ++ ) { sum += arr [ i ] ; if ( arr [ i ] % x == 0 && largestDivisible < arr [ i ] ) largestDivisible = arr [ i ] ; if ( arr [ i ] < minimum ) minimum = arr [ i ] ; } if ( largestDivisible == -1 ) return sum ; ll sumAfterOperation = sum - minimum - largestDivisible + ( x * minimum ) + ( largestDivisible / x ) ; return min ( sum , sumAfterOperation ) ; } int main ( ) { int arr [ ] = { 5 , 5 , 5 , 5 , 6 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int x = 3 ; cout << minSum ( arr , n , x ) ; return 0 ; } |
Maximum Bitwise AND pair from given range | C ++ implementation of the approach ; Function to return the maximum bitwise AND possible among all the possible pairs ; If there is only a single value in the range [ L , R ] ; If there are only two values in the range [ L , R ] ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxAND ( int L , int R ) { if ( L == R ) return L ; else if ( ( R - L ) == 1 ) return ( R & L ) ; else { if ( ( ( R - 1 ) & R ) > ( ( R - 2 ) & ( R - 1 ) ) ) return ( ( R - 1 ) & R ) ; else return ( ( R - 2 ) & ( R - 1 ) ) ; } } int main ( ) { int L = 1 , R = 632 ; cout << maxAND ( L , R ) ; return 0 ; } |
Smallest Special Prime which is greater than or equal to a given number | CPP program to find the Smallest Special Prime which is greater than or equal to a given number ; Function to check whether the number is a special prime or not ; While number is not equal to zero ; If the number is not prime return false . ; Else remove the last digit by dividing the number by 10. ; If the number has become zero then the number is special prime , hence return true ; Function to find the Smallest Special Prime which is greater than or equal to a given number ; Initially all numbers are considered Primes . ; There is always an answer possible ; Checking if the number is a special prime or not ; If yes print the number and break the loop . ; Else increment the number . ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkSpecialPrime ( bool * sieve , int num ) { while ( num ) { if ( ! sieve [ num ] ) { return false ; } num /= 10 ; } return true ; } void findSpecialPrime ( int N ) { bool sieve [ N * 10 ] ; memset ( sieve , true , sizeof ( sieve ) ) ; sieve [ 0 ] = sieve [ 1 ] = false ; for ( long long i = 2 ; i <= N * 10 ; i ++ ) { if ( sieve [ i ] ) { for ( long long j = i * i ; j <= N * 10 ; j += i ) { sieve [ j ] = false ; } } } while ( true ) { if ( checkSpecialPrime ( sieve , N ) ) { cout << N << ' ' ; break ; } else N ++ ; } } int main ( ) { int N = 379 ; findSpecialPrime ( N ) ; N = 100 ; findSpecialPrime ( N ) ; return 0 ; } |
Minimum number of given moves required to make N divisible by 25 | C ++ implementation of the approach ; Function to return the minimum number of moves required to make n divisible by 25 ; Convert number into string ; To store required answer ; Length of the string ; To check all possible pairs ; Make a duplicate string ; Number of swaps required to place ith digit in last position ; Number of swaps required to place jth digit in 2 nd last position ; Find first non zero digit ; Place first non zero digit in the first position ; Convert string to number ; If this number is divisible by 25 then cur is one of the possible answer ; If not possible ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minMoves ( long long n ) { string s = to_string ( n ) ; int ans = INT_MAX ; int len = s . size ( ) ; for ( int i = 0 ; i < len ; ++ i ) { for ( int j = 0 ; j < len ; ++ j ) { if ( i == j ) continue ; string t = s ; int cur = 0 ; for ( int k = i ; k < len - 1 ; ++ k ) { swap ( t [ k ] , t [ k + 1 ] ) ; ++ cur ; } for ( int k = j - ( j > i ) ; k < len - 2 ; ++ k ) { swap ( t [ k ] , t [ k + 1 ] ) ; ++ cur ; } int pos = -1 ; for ( int k = 0 ; k < len ; ++ k ) { if ( t [ k ] != '0' ) { pos = k ; break ; } } for ( int k = pos ; k > 0 ; -- k ) { swap ( t [ k ] , t [ k - 1 ] ) ; ++ cur ; } long long nn = atoll ( t . c_str ( ) ) ; if ( nn % 25 == 0 ) ans = min ( ans , cur ) ; } } if ( ans == INT_MAX ) return -1 ; return ans ; } int main ( ) { long long n = 509201 ; cout << minMoves ( n ) ; return 0 ; } |
Maximum positive integer divisible by C and is in the range [ A , B ] | C ++ implementation of the above approach ; Function to return the required number ; If b % c = 0 then b is the required number ; Else get the maximum multiple of c smaller than b ; Driver code | #include <iostream> NEW_LINE using namespace std ; int getMaxNum ( int a , int b , int c ) { if ( b % c == 0 ) return b ; int x = ( ( b / c ) * c ) ; if ( x >= a && x <= b ) return x ; else return -1 ; } int main ( ) { int a = 2 , b = 10 , c = 3 ; cout << getMaxNum ( a , b , c ) ; return 0 ; } |
Count of pairs ( x , y ) in an array such that x < y | C ++ implementation of the approach ; Function to return the number of pairs ( x , y ) such that x < y ; Length of the array ; Calculate the number valid pairs ; Return the count of valid pairs ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int getPairs ( int a [ ] ) { int n = sizeof ( a [ 0 ] ) ; int count = ( n * ( n - 1 ) ) / 2 ; return count ; } int main ( ) { int a [ ] = { 2 , 4 , 3 , 1 } ; cout << getPairs ( a ) ; return 0 ; } |
Count the total number of squares that can be visited by Bishop in one move | C ++ implementation of above approach ; Function to return the count of total positions the Bishop can visit in a single move ; Count top left squares ; Count bottom right squares ; Count top right squares ; Count bottom left squares ; Return total count ; Driver code ; Bishop 's Position | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countSquares ( int row , int column ) { int topLeft = min ( row , column ) - 1 ; int bottomRight = 8 - max ( row , column ) ; int topRight = min ( row , 9 - column ) - 1 ; int bottomLeft = 8 - max ( row , 9 - column ) ; return ( topLeft + topRight + bottomRight + bottomLeft ) ; } int main ( ) { int row = 4 , column = 4 ; cout << countSquares ( row , column ) ; return 0 ; } |
Check whether Bishop can take down Pawn or not | C ++ implementation of above approach ; Function that return true if the Bishop can take down the pawn ; If pawn is at angle 45 or 225 degree from bishop 's Position ; If pawn is at angle 135 or 315 degree from bishop 's Position ; Driver code ; Bishop 's Position ; Pawn 's Position | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool canTakeDown ( int bishopX , int bishopY , int pawnX , int pawnY ) { if ( pawnX - bishopX == pawnY - bishopY ) return true ; else if ( - pawnX + bishopX == pawnY - bishopY ) return true ; else return false ; } int main ( ) { int bishopX = 5 , bishopY = 5 ; int pawnX = 1 , pawnY = 1 ; if ( canTakeDown ( bishopX , bishopY , pawnX , pawnY ) ) cout << " Yes " ; else cout << " No " ; } |
Find maximum operations to reduce N to 1 | CPP program to find maximum number moves possible ; To store number of prime factors of each number ; Function to find number of prime factors of each number ; if i is a prime number ; increase value by one from it 's preveious multiple ; make prefix sum this will be helpful for multiple test cases ; Driver Code ; Generate primeFactors array ; required answer | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 1000005 NEW_LINE int primeFactors [ N ] ; void findPrimeFactors ( ) { for ( int i = 2 ; i < N ; i ++ ) if ( primeFactors [ i ] == 0 ) for ( int j = i ; j < N ; j += i ) primeFactors [ j ] = primeFactors [ j / i ] + 1 ; for ( int i = 1 ; i < N ; i ++ ) primeFactors [ i ] += primeFactors [ i - 1 ] ; } int main ( ) { findPrimeFactors ( ) ; int a = 6 , b = 3 ; cout << primeFactors [ a ] - primeFactors [ b ] ; return 0 ; } |
Smallest integer with digit sum M and multiple of N | C ++ implementation of the above approach ; Function to return digit sum ; Function to find out the smallest integer ; Start of the iterator ( Smallest multiple of n ) ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int digitSum ( int n ) { int ans = 0 ; while ( n ) { ans += n % 10 ; n /= 10 ; } return ans ; } int findInt ( int n , int m ) { int minDigit = floor ( m / 9 ) ; int start = pow ( 10 , minDigit ) - ( int ) pow ( 10 , minDigit ) % n ; while ( start < INT_MAX ) { if ( digitSum ( start ) == m ) return start ; else start += n ; } return -1 ; } int main ( ) { int n = 13 , m = 32 ; cout << findInt ( n , m ) ; return 0 ; } |
Maximum sum after repeatedly dividing N by a divisor | C ++ implementation of the above approach ; Function to find the smallest divisor ; Function to find the maximum sum ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int smallestDivisor ( int n ) { int mx = sqrt ( n ) ; for ( int i = 2 ; i <= mx ; i ++ ) if ( n % i == 0 ) return i ; return n ; } int maxSum ( int n ) { long long res = n ; while ( n > 1 ) { int divi = smallestDivisor ( n ) ; n /= divi ; res += n ; } return res ; } int main ( ) { int n = 34 ; cout << maxSum ( n ) ; return 0 ; } |
Make all elements of an array equal with the given operation | C ++ implementation of the approach ; Function that returns true if all the elements of the array can be made equal with the given operation ; To store the sum of the array elements and the maximum element from the array ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPossible ( int n , int k , int arr [ ] ) { int sum = arr [ 0 ] , maxVal = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { sum += arr [ i ] ; maxVal = max ( maxVal , arr [ i ] ) ; } if ( ( float ) maxVal > ( float ) ( sum + k ) / n ) return false ; return true ; } int main ( ) { int k = 8 ; int arr [ ] = { 1 , 2 , 3 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; if ( isPossible ( n , k , arr ) ) cout << " Yes " ; else cout << " No " ; return 0 ; } |
Maximize the value of x + y + z such that ax + by + cz = n | C ++ implementation of the approach ; Function to return the maximum value of ( x + y + z ) such that ( ax + by + cz = n ) ; i represents possible values of a * x ; j represents possible values of b * y ; If z is an integer ; Driver code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxResult ( int n , int a , int b , int c ) { int maxVal = 0 ; for ( int i = 0 ; i <= n ; i += a ) { for ( int j = 0 ; j <= n - i ; j += b ) { float z = ( float ) ( n - ( i + j ) ) / ( float ) ( c ) ; if ( floor ( z ) == ceil ( z ) ) { int x = i / a ; int y = j / b ; maxVal = max ( maxVal , x + y + ( int ) z ) ; } } } return maxVal ; } int main ( ) { int n = 10 , a = 5 , b = 3 , c = 4 ; cout << maxResult ( n , a , b , c ) ; return 0 ; } |
Make all numbers of an array equal | C ++ implementation of the approach ; Function that returns true if all the array elements can be made equal with the given operation ; Divide number by 2 ; Divide number by 3 ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool EqualNumbers ( int a [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) { while ( a [ i ] % 2 == 0 ) a [ i ] /= 2 ; while ( a [ i ] % 3 == 0 ) a [ i ] /= 3 ; if ( a [ i ] != a [ 0 ] ) { return false ; } } return true ; } int main ( ) { int a [ ] = { 50 , 75 , 150 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; if ( EqualNumbers ( a , n ) ) cout << " Yes " ; else cout << " No " ; return 0 ; } |
Maximum GCD from Given Product of Unknowns | C ++ implementation of the approach ; Function to return the required gcd ; Count the number of times 2 divides p ; Equivalent to p = p / 2 ; ; If 2 divides p ; Check all the possible numbers that can divide p ; If n in the end is a prime number ; Return the required gcd ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; long max_gcd ( long n , long p ) { int count = 0 ; long gcd = 1 ; while ( p % 2 == 0 ) { p >>= 1 ; count ++ ; } if ( count > 0 ) gcd *= ( long ) pow ( 2 , count / n ) ; for ( long i = 3 ; i <= sqrt ( p ) ; i += 2 ) { count = 0 ; while ( p % i == 0 ) { count ++ ; p = p / i ; } if ( count > 0 ) { gcd *= ( long ) pow ( i , count / n ) ; } } if ( p > 2 ) gcd *= ( long ) pow ( p , 1 / n ) ; return gcd ; } int main ( ) { long n = 3 ; long p = 80 ; cout << max_gcd ( n , p ) ; } |
Minimum positive integer divisible by C and is not in range [ A , B ] | C ++ implementation of the approach ; Function to return the required number ; If doesn 't belong to the range then c is the required number ; Else get the next multiple of c starting from b + 1 ; Driver code | #include <iostream> NEW_LINE using namespace std ; int getMinNum ( int a , int b , int c ) { if ( c < a c > b ) return c ; int x = ( ( b / c ) * c ) + c ; return x ; } int main ( ) { int a = 2 , b = 4 , c = 4 ; cout << getMinNum ( a , b , c ) ; return 0 ; } |
Count of pairs of ( i , j ) such that ( ( n % i ) % j ) % n is maximized | C ++ implementation of the approach ; Function to return the count of required pairs ; Special case ; Number which will give the max value for ( ( n % i ) % j ) % n ; To store the maximum possible value of ( ( n % i ) % j ) % n ; Count of possible pairs ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countPairs ( int n ) { if ( n == 2 ) return 4 ; int num = ( ( n / 2 ) + 1 ) ; int max = n % num ; int count = n - max ; return count ; } int main ( ) { int n = 5 ; cout << countPairs ( n ) ; } |
Remove characters from a numeric string such that string becomes divisible by 8 | C ++ program to remove digits from a numeric string such that the number becomes divisible by 8 ; Function that return true if sub is a sub - sequence in s ; Function to return a multiple of 8 formed after removing 0 or more characters from the given string ; Iterate over all multiples of 8 ; If current multiple exists as a subsequence in the given string ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int checkSub ( string sub , string s ) { int j = 0 ; for ( int i = 0 ; i < s . size ( ) ; i ++ ) if ( sub [ j ] == s [ i ] ) j ++ ; return j == ( int ) sub . size ( ) ; } int getMultiple ( string s ) { for ( int i = 0 ; i < 1e3 ; i += 8 ) { if ( checkSub ( to_string ( i ) , s ) ) return i ; } return -1 ; } int main ( ) { string s = "3454" ; cout << getMultiple ( s ) ; return 0 ; } |
Program to check if a number is divisible by any of its digits | C ++ implementation of above approach ; Converting integer to string ; Traversing the string ; find the actual digit ; If the number is divisible by digits then return yes ; If no digits are dividing the number then return no ; Driver Code ; passing this number to get result function | #include <bits/stdc++.h> NEW_LINE using namespace std ; string getResult ( int n ) { string st = to_string ( n ) ; for ( int i = 0 ; i < st . length ( ) ; i ++ ) { int d = st [ i ] - 48 ; if ( n % d == 0 ) { return " Yes " ; } } return " No " ; } int main ( ) { int n = 9876543 ; cout << getResult ( n ) ; } |
Program to find sum of harmonic series | CPP program to find sum of harmonic series using recursion ; Base condition ; Driven Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; float sum ( float n ) { if ( n < 2 ) return 1 ; else return 1 / n + ( sum ( n - 1 ) ) ; } int main ( ) { cout << ( sum ( 8 ) ) << endl ; cout << ( sum ( 10 ) ) << endl ; return 0 ; } |
Sum of P terms of an AP if Mth and Nth terms are given | C ++ implementation of the above approach ; Function to calculate the value of the ; Calculate value of d using formula ; Calculate value of a using formula ; Return pair ; Function to calculate value sum of first p numbers of the series ; First calculate value of a and d ; Calculate the sum by using formula ; Return the sum ; Driven Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; pair < double , double > findingValues ( double m , double n , double mth , double nth ) { double d = ( abs ( mth - nth ) ) / abs ( ( m - 1 ) - ( n - 1 ) ) ; double a = mth - ( ( m - 1 ) * d ) ; return make_pair ( a , d ) ; } double findSum ( int m , int n , int mth , int nth , int p ) { pair < double , double > ad ; ad = findingValues ( m , n , mth , nth ) ; double a = ad . first , d = ad . second ; double sum = ( p * ( 2 * a + ( p - 1 ) * d ) ) / 2 ; return sum ; } int main ( ) { double m = 6 , n = 10 , mTerm = 12 , nTerm = 20 , p = 5 ; cout << findSum ( m , n , mTerm , nTerm , p ) << endl ; return 0 ; } |
Print all integers that are sum of powers of two given numbers | C ++ implementation of the approach ; Function to print powerful integers ; Set is used to store distinct numbers in sorted order ; Store all the powers of y < bound in a vector to avoid calculating them again and again ; x ^ i ; If num is within limits insert it into the set ; Break out of the inner loop ; Adding any number to it will be out of bounds ; Increment i ; Print the contents of the set ; Driver code ; Print powerful integers | #include <bits/stdc++.h> NEW_LINE using namespace std ; void powerfulIntegers ( int x , int y , int bound ) { set < int > s ; vector < int > powersOfY ; int i ; powersOfY . push_back ( 1 ) ; for ( i = y ; i < bound && y != 1 ; i = i * y ) powersOfY . push_back ( i ) ; i = 0 ; while ( true ) { int xPowI = pow ( x , i ) ; for ( auto j = powersOfY . begin ( ) ; j != powersOfY . end ( ) ; ++ j ) { int num = xPowI + * j ; if ( num <= bound ) s . insert ( num ) ; else break ; } if ( xPowI >= bound x == 1 ) break ; i ++ ; } set < int > :: iterator itr ; for ( itr = s . begin ( ) ; itr != s . end ( ) ; itr ++ ) { cout << * itr << " β " ; } } int main ( ) { int x = 2 , y = 3 , bound = 10 ; powerfulIntegers ( x , y , bound ) ; return 0 ; } |
Distribute N candies among K people | C ++ code for better approach to distribute candies ; Function to find out the number of candies every person received ; Count number of complete turns ; Get the last term ; Stores the number of candies ; Last term of last and current series ; Sum of current and last series ; Sum of current series only ; If sum of current is less than N ; else Individually distribute ; First term ; Distribute candies till there ; Candies available ; Not available ; Count the total candies ; Print the total candies ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void candies ( int n , int k ) { int count = 0 ; int ind = 1 ; int arr [ k ] ; memset ( arr , 0 , sizeof ( arr ) ) ; while ( n ) { int f1 = ( ind - 1 ) * k ; int f2 = ind * k ; int sum1 = ( f1 * ( f1 + 1 ) ) / 2 ; int sum2 = ( f2 * ( f2 + 1 ) ) / 2 ; int res = sum2 - sum1 ; if ( res <= n ) { count ++ ; n -= res ; ind ++ ; } { int i = 0 ; int term = ( ( ind - 1 ) * k ) + 1 ; while ( n > 0 ) { if ( term <= n ) { arr [ i ++ ] = term ; n -= term ; term ++ ; } else { arr [ i ++ ] = n ; n = 0 ; } } } } for ( int i = 0 ; i < k ; i ++ ) arr [ i ] += ( count * ( i + 1 ) ) + ( k * ( count * ( count - 1 ) ) / 2 ) ; for ( int i = 0 ; i < k ; i ++ ) cout << arr [ i ] << " β " ; } int main ( ) { int n = 10 , k = 3 ; candies ( n , k ) ; return 0 ; } |
Distribute N candies among K people | C ++ implementation of the above approach ; Function to find out the number of candies every person received ; Count number of complete turns ; Get the last term ; Stores the number of candies ; Do a binary search to find the number whose sum is less than N . ; Get mide ; If sum is below N ; Find number of complete turns ; Right halve ; Left halve ; Last term of last complete series ; Subtract the sum till ; First term of incomplete series ; Count the total candies ; Print the total candies ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void candies ( int n , int k ) { int count = 0 ; int ind = 1 ; int arr [ k ] ; memset ( arr , 0 , sizeof ( arr ) ) ; int low = 0 , high = n ; while ( low <= high ) { int mid = ( low + high ) >> 1 ; int sum = ( mid * ( mid + 1 ) ) >> 1 ; if ( sum <= n ) { count = mid / k ; low = mid + 1 ; } else { high = mid - 1 ; } } int last = ( count * k ) ; n -= ( last * ( last + 1 ) ) / 2 ; int i = 0 ; int term = ( count * k ) + 1 ; while ( n ) { if ( term <= n ) { arr [ i ++ ] = term ; n -= term ; term ++ ; } else { arr [ i ] += n ; n = 0 ; } } for ( int i = 0 ; i < k ; i ++ ) arr [ i ] += ( count * ( i + 1 ) ) + ( k * ( count * ( count - 1 ) ) / 2 ) ; for ( int i = 0 ; i < k ; i ++ ) cout << arr [ i ] << " β " ; } int main ( ) { int n = 7 , k = 4 ; candies ( n , k ) ; return 0 ; } |
Smallest multiple of 3 which consists of three given non | C ++ implementation of the approach ; Function to return the minimum number divisible by 3 formed by the given digits ; Sort the given array in ascending ; Check if any single digit is divisible by 3 ; Check if any two digit number formed by the given digits is divisible by 3 starting from the minimum ; Generate the two digit number ; If none of the above is true , we can form three digit number by taking a [ 0 ] three times . ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int printSmallest ( int a [ 3 ] ) { int sum , sum1 ; sort ( a , a + 3 ) ; int i , j , k , num ; for ( int i = 0 ; i < 3 ; i ++ ) { if ( a [ i ] % 3 == 0 ) return a [ i ] ; } for ( i = 0 ; i < 3 ; i ++ ) { for ( j = 0 ; j < 3 ; j ++ ) { num = ( a [ i ] * 10 ) + a [ j ] ; if ( num % 3 == 0 ) return num ; } } return a [ 0 ] * 100 + a [ 0 ] * 10 + a [ 0 ] ; } int main ( ) { int arr [ ] = { 7 , 7 , 1 } ; cout << printSmallest ( arr ) ; return 0 ; } |
Print matrix after applying increment operations in M ranges | C ++ implementation of the approach ; Function to update and print the matrix after performing queries ; Add 1 to the first element of the sub - matrix ; If there is an element after the last element of the sub - matrix then decrement it by 1 ; Calculate the running sum ; Print the updated element ; Next line ; Driver code ; Size of the matrix ; Queries | #include <bits/stdc++.h> NEW_LINE using namespace std ; void updateMatrix ( int n , int q [ 3 ] [ 4 ] ) { int i , j ; int mat [ n ] [ n ] ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = 0 ; j < n ; j ++ ) mat [ i ] [ j ] = 0 ; for ( i = 0 ; i < 3 ; i ++ ) { int X1 = q [ i ] [ 0 ] ; int Y1 = q [ i ] [ 1 ] ; int X2 = q [ i ] [ 2 ] ; int Y2 = q [ i ] [ 3 ] ; mat [ X1 ] [ Y1 ] ++ ; if ( Y2 + 1 < n ) mat [ X2 ] [ Y2 + 1 ] -- ; else if ( X2 + 1 < n ) mat [ X2 + 1 ] [ 0 ] -- ; } int sum = 0 ; for ( i = 0 ; i < n ; i ++ ) { for ( j = 0 ; j < n ; j ++ ) { sum += mat [ i ] [ j ] ; cout << sum << " β " ; } cout << endl ; } } int main ( ) { int n = 5 ; int q [ 3 ] [ 4 ] = { { 0 , 0 , 1 , 2 } , { 1 , 2 , 3 , 4 } , { 1 , 4 , 3 , 4 } } ; updateMatrix ( n , q ) ; return 0 ; } |
Replace the maximum element in the array by coefficient of range | C ++ implementation to replace maximum element by coefficient of range ; Utility function to print the contents of the array ; Function to replace the maximum element from the array with the coefficient of range of the array ; Maximum element from the array ; Minimum element from the array ; Calculate the coefficient of range for the array ; Assuming all the array elements are distinc Replace the maximum element with the coefficient of range of the array ; Print the updated array ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printArr ( float arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " β " ; } void replaceMax ( float arr [ ] , int n ) { float max = * std :: max_element ( arr , arr + n ) ; float min = * std :: min_element ( arr , arr + n ) ; float range = max - min ; float coeffOfRange = range / ( max + min ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] == max ) { arr [ i ] = coeffOfRange ; break ; } } printArr ( arr , n ) ; } int main ( ) { float arr [ ] = { 15 , 16 , 10 , 9 , 6 , 7 , 17 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; replaceMax ( arr , n ) ; return 0 ; } |
Divide the two given numbers by their common divisors | C ++ implementation of above approach ; print the numbers after dividing them by their common factors ; iterate from 1 to minimum of a and b ; if i is the common factor of both the numbers ; Driver code ; divide A and B by their common factors | #include <bits/stdc++.h> NEW_LINE using namespace std ; void divide ( int a , int b ) { for ( int i = 2 ; i <= min ( a , b ) ; i ++ ) { while ( a % i == 0 && b % i == 0 ) { a = a / i ; b = b / i ; } } cout << " A β = β " << a << " , β B β = β " << b << endl ; } int main ( ) { int A = 10 , B = 15 ; divide ( A , B ) ; return 0 ; } |
Divide the two given numbers by their common divisors | C ++ implementation of above approach ; Function to calculate gcd of two numbers ; Function to calculate all common divisors of two given numbers a , b -- > input integer numbers ; find gcd of a , b ; 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 ) ; } void commDiv ( int a , int b ) { int n = gcd ( a , b ) ; a = a / n ; b = b / n ; cout << " A β = β " << a << " , β B β = β " << b << endl ; } int main ( ) { int a = 10 , b = 15 ; commDiv ( a , b ) ; return 0 ; } |
Minimum absolute difference between N and a power of 2 | C ++ implementation of the above approach ; Function to return the minimum difference between N and a power of 2 ; Power of 2 closest to n on its left ; Power of 2 closest to n on its right ; Return the minimum abs difference ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minAbsDiff ( int n ) { int left = 1 << ( ( int ) floor ( log2 ( n ) ) ) ; int right = left * 2 ; return min ( ( n - left ) , ( right - n ) ) ; } int main ( ) { int n = 15 ; cout << minAbsDiff ( n ) ; return 0 ; } |
Find probability that a player wins when probabilities of hitting the target are given | C ++ implementation of the approach ; Function to return the probability of the winner ; Driver Code ; Will print 9 digits after the decimal point | #include <bits/stdc++.h> NEW_LINE using namespace std ; double find_probability ( double p , double q , double r , double s ) { double t = ( 1 - p / q ) * ( 1 - r / s ) ; double ans = ( p / q ) / ( 1 - t ) ; return ans ; } int main ( ) { double p = 1 , q = 2 , r = 1 , s = 2 ; cout << fixed << setprecision ( 9 ) << find_probability ( p , q , r , s ) ; return 0 ; } |
Represent n as the sum of exactly k powers of two | Set 2 | C ++ implementation of the above approach ; Function to print k numbers which are powers of two and whose sum is equal to n ; Initialising the sum with k ; Initialising an array A with k elements and filling all elements with 1 ; Iterating A [ ] from k - 1 to 0 ; Update sum and A [ i ] till sum + A [ i ] is less than equal to n ; Impossible to find the combination ; Possible solution is stored in A [ ] ; Driver code | #include <iostream> NEW_LINE using namespace std ; void FindAllElements ( int n , int k ) { int sum = k ; int A [ k ] ; fill ( A , A + k , 1 ) ; for ( int i = k - 1 ; i >= 0 ; -- i ) { while ( sum + A [ i ] <= n ) { sum += A [ i ] ; A [ i ] *= 2 ; } } if ( sum != n ) { cout << " Impossible " ; } else { for ( int i = 0 ; i < k ; ++ i ) cout << A [ i ] << ' β ' ; } } int main ( ) { int n = 12 ; int k = 6 ; FindAllElements ( n , k ) ; return 0 ; } |
Check whether a + b = c or not after removing all zeroes from a , b and c | C ++ program to check the sum after Removing all zeroes is true or not ; Function to remove zeroes ; Initialize result to zero holds the Result after removing zeroes from no ; Initialize variable d to 1 that holds digits of no ; Loop while n is greater then zero ; Check if n mod 10 is not equal to zero ; store the result by removing zeroes And increment d by 10 ; Go to the next digit ; Return the result ; Function to check if sum is true after Removing all zeroes . ; Call removeZero ( ) for both sides and check whether they are equal After removing zeroes . ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int removeZero ( int n ) { int res = 0 ; int d = 1 ; while ( n > 0 ) { if ( n % 10 != 0 ) { res += ( n % 10 ) * d ; d *= 10 ; } n /= 10 ; } return res ; } bool isEqual ( int a , int b ) { if ( removeZero ( a ) + removeZero ( b ) == removeZero ( a + b ) ) return true ; return false ; } int main ( ) { int a = 105 , b = 106 ; isEqual ( a , b ) ? cout << " Yes " : cout << " No " ; return 0 ; } |
A Sum Array Puzzle | C ++ implementation of above approach ; Allocate memory for temporary arrays leftSum [ ] , rightSum [ ] and Sum [ ] ; Left most element of left array is always 0 ; Rightmost most element of right array is always 0 ; Construct the left array ; Construct the right array ; Construct the sum array using left [ ] and right [ ] ; print the constructed prod array ; Driver program to test above functions | #include <bits/stdc++.h> NEW_LINE using namespace std ; void sumArray ( int arr [ ] , int n ) { int leftSum [ n ] , rightSum [ n ] , Sum [ n ] , i , j ; leftSum [ 0 ] = 0 ; rightSum [ n - 1 ] = 0 ; for ( i = 1 ; i < n ; i ++ ) leftSum [ i ] = arr [ i - 1 ] + leftSum [ i - 1 ] ; for ( j = n - 2 ; j >= 0 ; j -- ) rightSum [ j ] = arr [ j + 1 ] + rightSum [ j + 1 ] ; for ( i = 0 ; i < n ; i ++ ) Sum [ i ] = leftSum [ i ] + rightSum [ i ] ; for ( i = 0 ; i < n ; i ++ ) cout << Sum [ i ] << " β " ; } int main ( ) { int arr [ ] = { 3 , 6 , 4 , 8 , 9 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; sumArray ( arr , n ) ; return 0 ; } |
Find minimum x such that ( x % k ) * ( x / k ) == n | Set | CPP Program to find the minimum positive X such that the given equation holds true ; This function gives the required answer ; Iterate for all the factors ; Check if i is a factor ; Consider i to be A and n / i to be B ; Consider i to be B and n / i to be A ; Driver Code to test above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minimumX ( int n , int k ) { int mini = INT_MAX ; for ( int i = 1 ; i * i <= n ; i ++ ) { if ( n % i == 0 ) { int fir = i ; int sec = n / i ; int num1 = fir * k + sec ; int res = ( num1 / k ) * ( num1 % k ) ; if ( res == n ) mini = min ( num1 , mini ) ; int num2 = sec * k + fir ; res = ( num2 / k ) * ( num2 % k ) ; if ( res == n ) mini = min ( num2 , mini ) ; } } return mini ; } int main ( ) { int n = 4 , k = 6 ; cout << minimumX ( n , k ) << endl ; n = 5 , k = 5 ; cout << minimumX ( n , k ) << endl ; return 0 ; } |
Find minimum x such that ( x % k ) * ( x / k ) == n | CPP Program to find the minimum positive X such that the given equation holds true ; This function gives the required answer ; Iterate over all possible remainders ; it must divide n ; Driver Code to test above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minimumX ( int n , int k ) { int ans = INT_MAX ; for ( int rem = k - 1 ; rem > 0 ; rem -- ) { if ( n % rem == 0 ) ans = min ( ans , rem + ( n / rem ) * k ) ; } return ans ; } int main ( ) { int n = 4 , k = 6 ; cout << minimumX ( n , k ) << endl ; n = 5 , k = 5 ; cout << minimumX ( n , k ) << endl ; return 0 ; } |
Find nth Hermite number | C ++ program to find nth Hermite number ; Function to return nth Hermite number ; Base conditions ; Driver Code ; Print nth Hermite number | #include <bits/stdc++.h> NEW_LINE using namespace std ; int getHermiteNumber ( int n ) { if ( n == 0 ) return 1 ; if ( n == 1 ) return 0 ; else return -2 * ( n - 1 ) * getHermiteNumber ( n - 2 ) ; } int main ( ) { int n = 6 ; cout << getHermiteNumber ( n ) ; return 0 ; } |
Find numbers a and b that satisfy the given conditions | C ++ implementation of the above approach ; Function to print the required numbers ; Suppose b = n and we want a % b = 0 and also ( a / b ) < n so a = b * ( n - 1 ) ; Special case if n = 1 we get a = 0 so ( a * b ) < n ; If no pair satisfies the conditions ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void find ( int n ) { int b = n ; int a = b * ( n - 1 ) ; if ( a * b > n && a / b < n ) { cout << " a β = β " << a << " , β b β = β " << b ; } else cout << -1 << endl ; } int main ( ) { int n = 10 ; find ( n ) ; return 0 ; } |
Closest perfect square and its distance | CPP program to find the closest perfect square taking minimum steps to reach from a number ; Function to check if a number is perfect square or not ; Function to find the closest perfect square taking minimum steps to reach from a number ; Variables to store first perfect square number above and below N ; Finding first perfect square number greater than N ; Finding first perfect square number less than N ; Variables to store the differences ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPerfect ( int N ) { if ( ( sqrt ( N ) - floor ( sqrt ( N ) ) ) != 0 ) return false ; return true ; } void getClosestPerfectSquare ( int N ) { if ( isPerfect ( N ) ) { cout << N << " β " << "0" << endl ; return ; } int aboveN = -1 , belowN = -1 ; int n1 ; n1 = N + 1 ; while ( true ) { if ( isPerfect ( n1 ) ) { aboveN = n1 ; break ; } else n1 ++ ; } n1 = N - 1 ; while ( true ) { if ( isPerfect ( n1 ) ) { belowN = n1 ; break ; } else n1 -- ; } int diff1 = aboveN - N ; int diff2 = N - belowN ; if ( diff1 > diff2 ) cout << belowN << " β " << diff2 ; else cout << aboveN << " β " << diff1 ; } int main ( ) { int N = 1500 ; getClosestPerfectSquare ( N ) ; } |
Fraction | C ++ program to add 2 fractions ; Function to return gcd of a and b ; Function to convert the obtained fraction into it 's simplest form ; Finding gcd of both terms ; Converting both terms into simpler terms by dividing them by common factor ; Function to add two fractions ; Finding gcd of den1 and den2 ; Denominator of final fraction obtained finding LCM of den1 and den2 LCM * GCD = a * b ; Changing the fractions to have same denominator Numerator of the final fraction obtained ; Calling function to convert final fraction into it 's simplest form ; Driver program | #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 ) ; } void lowest ( int & den3 , int & num3 ) { int common_factor = gcd ( num3 , den3 ) ; den3 = den3 / common_factor ; num3 = num3 / common_factor ; } void addFraction ( int num1 , int den1 , int num2 , int den2 , int & num3 , int & den3 ) { den3 = gcd ( den1 , den2 ) ; den3 = ( den1 * den2 ) / den3 ; num3 = ( num1 ) * ( den3 / den1 ) + ( num2 ) * ( den3 / den2 ) ; lowest ( den3 , num3 ) ; } int main ( ) { int num1 = 1 , den1 = 500 , num2 = 2 , den2 = 1500 , den3 , num3 ; addFraction ( num1 , den1 , num2 , den2 , num3 , den3 ) ; printf ( " % d / % d β + β % d / % d β is β equal β to β % d / % d STRNEWLINE " , num1 , den1 , num2 , den2 , num3 , den3 ) ; return 0 ; } |
Largest Divisor of a Number not divisible by a perfect square | Efficient C ++ Program to find the largest divisor not divisible by any perfect square greater than 1 ; Function to find the largest divisor not divisible by any perfect square greater than 1 ; If the number is divisible by i * i , then remove one i ; Now all squares are removed from n ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findLargestDivisor ( int n ) { for ( int i = 2 ; i < sqrt ( n ) + 1 ; i ++ ) { while ( n % ( i * i ) == 0 ) { n = n / i ; } } return n ; } int main ( ) { int n = 12 ; cout << findLargestDivisor ( n ) << endl ; n = 97 ; cout << findLargestDivisor ( n ) << endl ; return 0 ; } |
Arithmetic Progression | C ++ program to check if a given array can form arithmetic progression ; Returns true if a permutation of arr [ 0. . n - 1 ] can form arithmetic progression ; Sort array ; After sorting , difference between consecutive elements must be same . ; Driven Program | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkIsAP ( int arr [ ] , int n ) { if ( n == 1 ) return true ; sort ( arr , arr + n ) ; int d = arr [ 1 ] - arr [ 0 ] ; for ( int i = 2 ; i < n ; i ++ ) if ( arr [ i ] - arr [ i - 1 ] != d ) return false ; return true ; } int main ( ) { int arr [ ] = { 20 , 15 , 5 , 0 , 10 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; ( checkIsAP ( arr , n ) ) ? ( cout << " Yes " << endl ) : ( cout << " No " << endl ) ; return 0 ; } |
Check if a number is Triperfect Number | CPP code to check if a given number is Triperfect or not ; Returns true if n is Triperfect ; To store sum of divisors . Adding 1 and n since they are divisors of n . ; Find all divisors and add them ; If sum of divisors is equal to 3 * n , then n is a Triperfect number ; Driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isTriPerfect ( int n ) { int sum = 1 + n ; int i = 2 ; while ( i * i <= n ) { if ( n % i == 0 ) { if ( n / i == i ) sum = sum + i ; else sum = sum + i + n / i ; } i += 1 ; } if ( sum == 3 * n and n != 1 ) return true ; else false ; } int main ( ) { int n = 120 ; if ( isTriPerfect ( n ) ) cout << n << " β is β a β Triperfect β number " ; } |
Sum of first N natural numbers which are divisible by X or Y | C ++ program to find sum of numbers from 1 to N which are divisible by X or Y ; Function to calculate the sum of numbers divisible by X or Y ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int sum ( int N , int X , int Y ) { int S1 , S2 , S3 ; S1 = ( ( N / X ) ) * ( 2 * X + ( N / X - 1 ) * X ) / 2 ; S2 = ( ( N / Y ) ) * ( 2 * Y + ( N / Y - 1 ) * Y ) / 2 ; S3 = ( ( N / ( X * Y ) ) ) * ( 2 * ( X * Y ) + ( N / ( X * Y ) - 1 ) * ( X * Y ) ) / 2 ; return S1 + S2 - S3 ; } int main ( ) { int N = 14 ; int X = 3 , Y = 5 ; cout << sum ( N , X , Y ) ; return 0 ; } |
Count numbers from range whose prime factors are only 2 and 3 | C ++ program to count the numbers within a range whose prime factors are only 2 and 3 ; Function to count the number within a range whose prime factors are only 2 and 3 ; Start with 2 so that 1 doesn 't get counted ; While num is divisible by 2 , divide it by 2 ; While num is divisible by 3 , divide it by 3 ; If num got reduced to 1 then it has only 2 and 3 as prime factors ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findTwoThreePrime ( int l , int r ) { if ( l == 1 ) l ++ ; int count = 0 ; for ( int i = l ; i <= r ; i ++ ) { int num = i ; while ( num % 2 == 0 ) num /= 2 ; while ( num % 3 == 0 ) num /= 3 ; if ( num == 1 ) count ++ ; } return count ; } int main ( ) { int l = 1 , r = 10 ; cout << findTwoThreePrime ( l , r ) ; return 0 ; } |
Maximum number with same digit factorial product | C ++ implementation of the approach ; Function to return the required number ; Count the frequency of each digit ; 4 ! can be expressed as 2 ! * 2 ! * 3 ! ; 6 ! can be expressed as 5 ! * 3 ! ; 8 ! can be expressed as 7 ! * 2 ! * 2 ! * 2 ! ; 9 ! can be expressed as 7 ! * 3 ! * 3 ! * 2 ! ; To store the required number ; If number has only either 1 and 0 as its digits ; Generate the greatest number possible ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; string getNumber ( string s ) { int number_of_digits = s . length ( ) ; int freq [ 10 ] = { 0 } ; for ( int i = 0 ; i < number_of_digits ; i ++ ) { if ( s [ i ] == '1' s [ i ] == '2' s [ i ] == '3' s [ i ] == '5' s [ i ] == '7' ) { freq [ s [ i ] - 48 ] += 1 ; } if ( s [ i ] == '4' ) { freq [ 2 ] += 2 ; freq [ 3 ] ++ ; } if ( s [ i ] == '6' ) { freq [ 5 ] ++ ; freq [ 3 ] ++ ; } if ( s [ i ] == '8' ) { freq [ 7 ] ++ ; freq [ 2 ] += 3 ; } if ( s [ i ] == '9' ) { freq [ 7 ] ++ ; freq [ 3 ] += 2 ; freq [ 2 ] ++ ; } } string t = " " ; if ( freq [ 1 ] == number_of_digits || freq [ 0 ] == number_of_digits || ( freq [ 0 ] + freq [ 1 ] ) == number_of_digits ) { return s ; } else { for ( int i = 9 ; i >= 2 ; i -- ) { int ctr = freq [ i ] ; while ( ctr -- ) { t += ( char ) ( i + 48 ) ; } } return t ; } } int main ( ) { string s = "1280" ; cout << getNumber ( s ) ; return 0 ; } |
Program to find first N Iccanobif Numbers | C ++ program to find first N Icanobif numbers ; Iterative function to reverse digits of num ; Function to print first N Icanobif Numbers ; Initialize first , second numbers ; Print first two numbers ; Reversing digit of previous two terms and adding them ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int reversDigits ( int num ) { int rev_num = 0 ; while ( num > 0 ) { rev_num = rev_num * 10 + num % 10 ; num = num / 10 ; } return rev_num ; } void icanobifNumbers ( int N ) { int first = 0 , second = 1 ; if ( N == 1 ) cout << first ; else if ( N == 2 ) cout << first << " β " << second ; else { cout << first << " β " << second << " β " ; for ( int i = 3 ; i <= N ; i ++ ) { int x = reversDigits ( first ) ; int y = reversDigits ( second ) ; cout << x + y << " β " ; int temp = second ; second = x + y ; first = temp ; } } } int main ( ) { int N = 12 ; icanobifNumbers ( N ) ; return 0 ; } |
Add N digits to A such that it is divisible by B after each addition | C ++ implementation of the approach ; Try all digits from ( 0 to 9 ) ; Fails in the first move itself ; Add ( n - 1 ) 0 's ; Driver Program to test above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; int addNDigits ( int a , int b , int n ) { int num = a ; for ( int i = 0 ; i <= 9 ; i ++ ) { int tmp = a * 10 + i ; if ( tmp % b == 0 ) { a = tmp ; break ; } } if ( num == a ) return -1 ; for ( int j = 0 ; j < n - 1 ; j ++ ) a *= 10 ; return a ; } int main ( ) { int a = 5 , b = 3 , n = 3 ; cout << addNDigits ( a , b , n ) ; return 0 ; } |
Count number of triplets ( a , b , c ) such that a ^ 2 + b ^ 2 = c ^ 2 and 1 <= a <= b <= c <= n | C ++ program to Find number of Triplets 1 <= a <= b <= c <= n , Such that a ^ 2 + b ^ 2 = c ^ 2 ; function to ind number of Triplets 1 <= a <= b <= c <= n , Such that a ^ 2 + b ^ 2 = c ^ 2 ; to store required answer ; run nested loops for first two numbers . ; third number ; check if third number is perfect square and less than n ; Driver code ; function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int Triplets ( int n ) { int ans = 0 ; for ( int i = 1 ; i <= n ; ++ i ) { for ( int j = i ; j <= n ; ++ j ) { int x = i * i + j * j ; int y = sqrt ( x ) ; if ( y * y == x && y <= n ) ++ ans ; } } return ans ; } int main ( ) { int n = 10 ; cout << Triplets ( n ) ; return 0 ; } |
Sum of the digits of a number N written in all bases from 2 to N / 2 | C ++ implementation of the approach ; Function to calculate the sum of the digits of n in the given base ; Sum of digits ; Digit of n in the given base ; Add the digit ; Function to calculate the sum of digits of n in bases from 2 to n / 2 ; to store digit sum in all bases ; function call for multiple bases ; Driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; int solve ( int n , int base ) { int sum = 0 ; while ( n > 0 ) { int remainder = n % base ; sum += remainder ; n = n / base ; } return sum ; } void SumsOfDigits ( int n ) { int sum = 0 ; for ( int base = 2 ; base <= n / 2 ; ++ base ) sum += solve ( n , base ) ; cout << sum ; } int main ( ) { int n = 8 ; SumsOfDigits ( n ) ; return 0 ; } |
Largest number in an array that is not a perfect cube | CPP program to find the largest non - perfect cube number among n numbers ; Function to check if a number is perfect cube number or not ; takes the sqrt of the number ; checks if it is a perfect cube number ; Function to find the largest non perfect cube number in the array ; stores the maximum of all perfect cube numbers ; Traverse all elements in the array ; store the maximum if current element is a non perfect cube ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkPerfectcube ( int n ) { int d = cbrt ( n ) ; if ( d * d * d == n ) return true ; return false ; } int largestNonPerfectcubeNumber ( int a [ ] , int n ) { int maxi = -1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( ! checkPerfectcube ( a [ i ] ) ) maxi = max ( a [ i ] , maxi ) ; } return maxi ; } int main ( ) { int a [ ] = { 16 , 64 , 25 , 2 , 3 , 10 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << largestNonPerfectcubeNumber ( a , n ) ; return 0 ; } |
Check if N can be represented as sum of integers chosen from set { A , B } | CPP program to find if number N can be represented as sum of a ' s β and β b ' s ; Function to find if number N can be represented as sum of a ' s β and β b ' s ; base condition ; if x is already visited ; set x as possible ; recursive call ; Driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; void checkIfPossibleRec ( int x , int a , int b , bool isPossible [ ] , int n ) { if ( x > n ) return ; if ( isPossible [ x ] ) return ; isPossible [ x ] = true ; checkIfPossibleRec ( x + a , a , b , isPossible , n ) ; checkIfPossibleRec ( x + b , a , b , isPossible , n ) ; } bool checkPossible ( int n , int a , int b ) { bool isPossible [ n + 1 ] = { false } ; checkIfPossibleRec ( 0 , a , b , isPossible , n ) ; return isPossible [ n ] ; } int main ( ) { int a = 3 , b = 7 , n = 8 ; if ( checkPossible ( a , b , n ) ) cout << " Yes " ; else cout << " No " ; return 0 ; } |
Sum of all odd natural numbers in range L and R | C ++ program to print the sum of all numbers in range L and R ; Function to return the sum of all odd natural numbers ; Function to return the sum of all odd numbers in range L and R ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int sumOdd ( int n ) { int terms = ( n + 1 ) / 2 ; int sum = terms * terms ; return sum ; } int suminRange ( int l , int r ) { return sumOdd ( r ) - sumOdd ( l - 1 ) ; } int main ( ) { int l = 2 , r = 5 ; cout << " Sum β of β odd β natural β numbers β from β L β to β R β is β " << suminRange ( l , r ) ; return 0 ; } |
Sum of common divisors of two numbers A and B | C ++ implementation of above approach ; Function to calculate gcd of two numbers ; Function to calculate all common divisors of two given numbers a , b -- > input integer numbers ; find gcd of a , b ; Find the sum of divisors of n . ; if ' i ' is factor of n ; check if divisors are equal ; Driver program to run the case | #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 sumcommDiv ( int a , int b ) { int n = gcd ( a , b ) ; int sum = 0 ; for ( int i = 1 ; i <= sqrt ( n ) ; i ++ ) { if ( n % i == 0 ) { if ( n / i == i ) sum += i ; else sum += ( n / i ) + i ; } } return sum ; } int main ( ) { int a = 10 , b = 15 ; cout << " Sum β = β " << sumcommDiv ( a , b ) ; return 0 ; } |
Check if a number is formed by Concatenation of 1 , 14 or 144 only | C ++ program to check if a number is formed by Concatenation of 1 , 14 or 144 only ; Function to check if a number is formed by Concatenation of 1 , 14 or 144 only ; check for each possible digit if given number consist other then 1 , 14 , 144 print NO else print YES ; Driver Code | #include <iostream> NEW_LINE using namespace std ; string checkNumber ( int N ) { int temp = N ; while ( temp > 0 ) { if ( temp % 1000 == 144 ) temp /= 1000 ; else if ( temp % 100 == 14 ) temp /= 100 ; else if ( temp % 10 == 1 ) temp /= 10 ; else { return " NO " ; } } return " YES " ; } int main ( ) { int N = 1414 ; cout << checkNumber ( N ) ; return 0 ; } |
Fibonacci problem ( Value of Fib ( N ) * Fib ( N ) | C ++ implementation of the approach ; Driver code | #include <iostream> NEW_LINE using namespace std ; int getResult ( int n ) { if ( n & 1 ) return 1 ; return -1 ; } int main ( ) { int n = 3 ; cout << getResult ( n ) ; } |
Find two numbers with sum and product both same as N | C ++ program to find a and b such that a * b = N and a + b = N ; Function to return the smallest string ; Not possible ; find a and b ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findAandB ( double N ) { double val = N * N - 4.0 * N ; if ( val < 0 ) { cout << " NO " ; return ; } double a = ( N + sqrt ( val ) ) / 2.0 ; double b = ( N - sqrt ( val ) ) / 2.0 ; cout << " a β = β " << a << endl ; cout << " b β = β " << b << endl ; } int main ( ) { double N = 69.0 ; findAandB ( N ) ; return 0 ; } |
Find minimum operations needed to make an Array beautiful | CPP implementation of above approach ; Function to find minimum operations required to make array beautiful ; counting consecutive zeros . ; check that start and end are same ; check is zero and one are equal ; Driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minOperations ( int A [ ] , int n ) { if ( n & 1 ) return -1 ; int zeros = 0 , consZeros = 0 , ones = 0 ; for ( int i = 0 ; i < n ; ++ i ) { A [ i ] == 0 ? zeros ++ : ones ++ ; if ( i + 1 < n ) { if ( A [ i ] == 0 && A [ i + 1 ] == 0 ) consZeros ++ ; } } if ( A [ 0 ] == A [ n - 1 ] && A [ 0 ] == 0 ) consZeros ++ ; if ( zeros == ones ) return consZeros ; else return -1 ; } int main ( ) { int A [ ] = { 1 , 1 , 0 , 0 } ; int n = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << minOperations ( A , n ) ; return 0 ; } |
Steps to reduce N to zero by subtracting its most significant digit at every step | C ++ program to find the count of Steps to reduce N to zero by subtracting its most significant digit at every step ; Function to count the number of digits in a number m ; Function to count the number of steps to reach 0 ; count the total number of stesp ; iterate till we reach 0 ; count the digits in last ; decrease it by 1 ; find the number on whose division , we get the first digit ; first digit in last ; find the first number less than last where the first digit changes ; find the number of numbers with same first digit that are jumped ; count the steps ; the next number with a different first digit ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countdig ( int m ) { if ( m == 0 ) return 0 ; else return 1 + countdig ( m / 10 ) ; } int countSteps ( int x ) { int c = 0 ; int last = x ; while ( last ) { int digits = countdig ( last ) ; digits -= 1 ; int divisor = pow ( 10 , digits ) ; int first = last / divisor ; int lastnumber = first * divisor ; int skipped = ( last - lastnumber ) / first ; skipped += 1 ; c += skipped ; last = last - ( first * skipped ) ; } return c ; } int main ( ) { int n = 14 ; cout << countSteps ( n ) ; return 0 ; } |
GCD of a number raised to some power and another number | C ++ program of the above approach ; Calculates modular exponentiation , i . e . , ( 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 ; Returns GCD of a ^ n and b ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; typedef long long int ll ; ll power ( ll x , ll y , ll p ) { while ( y > 0 ) { if ( y & 1 ) res = ( res * x ) % p ; x = ( x * x ) % p ; } return res ; } ll gcd ( ll a , ll b ) { if ( a == 0 ) return b ; return gcd ( b % a , a ) ; } ll powerGCD ( ll a , ll b , ll n ) { ll e = power ( a , n , b ) ; return gcd ( e , b ) ; } int main ( ) { ll a = 5 , b = 4 , n = 2 ; cout << powerGCD ( a , b , n ) ; return 0 ; } |
Largest number not greater than N all the digits of which are odd | CPP program to print the largest integer not greater than N with all odd digits ; Function to check if all digits of a number are odd ; iterate for all digits ; if digit is even ; all digits are odd ; function to return the largest number with all digits odd ; iterate till we find a number with all digits odd ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool allOddDigits ( int n ) { while ( n ) { if ( ( n % 10 ) % 2 == 0 ) return false ; n /= 10 ; } return true ; } int largestNumber ( int n ) { if ( n % 2 == 0 ) n -- ; for ( int i = n ; ; i -= 2 ) if ( allOddDigits ( i ) ) return i ; } int main ( ) { int N = 23 ; cout << largestNumber ( N ) ; return 0 ; } |
Largest number not greater than N all the digits of which are odd | CPP program to print the largest integer not greater than N with all odd digits ; function to return the largest number with all digits odd ; convert the number to a string for easy operations ; find first even digit ; if no even digit , then N is the answer ; till first even digit , add all odd numbers ; decrease 1 from the even digit ; add 9 in the rest of the digits ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int largestNumber ( int n ) { 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 ++ ) { if ( ( ( s [ i ] - '0' ) % 2 & 1 ) == 0 ) { index = i ; break ; } } if ( index == -1 ) return duplicate ; int num = 0 ; 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 + 9 ; return num ; } int main ( ) { int N = 24578 ; cout << largestNumber ( N ) ; return 0 ; } |
Count number less than N which are product of perfect squares | C ++ program to count number less than N which are product of any two perfect squares ; Function to count number less than N which are product of any two perfect squares ; Driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countNumbers ( int N ) { return int ( sqrt ( N ) ) - 1 ; } int main ( ) { int N = 36 ; cout << countNumbers ( N ) ; return 0 ; } |
Count ordered pairs with product less than N | C ++ implementation of above approach ; Function to return count of Ordered pairs whose product are less than N ; Initialize count to 0 ; count total pairs ; multiply by 2 to get ordered_pairs ; subtract redundant pairs ( a , b ) where a == b . ; return answer ; Driver code ; function call to print required answer | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countOrderedPairs ( int N ) { int count_pairs = 0 ; for ( int i = 1 ; i <= sqrt ( N - 1 ) ; ++ i ) { for ( int j = i ; j * i < N ; ++ j ) ++ count_pairs ; } count_pairs *= 2 ; count_pairs -= int ( sqrt ( N - 1 ) ) ; return count_pairs ; } int main ( ) { int N = 5 ; cout << countOrderedPairs ( N ) ; return 0 ; } |
Absolute Difference of all pairwise consecutive elements in an array | C ++ program to print the absolute difference of the consecutive elements ; Function to print pairwise absolute difference of consecutive elements ; absolute difference between consecutive numbers ; Driver Code | #include <iostream> NEW_LINE using namespace std ; void pairwiseDifference ( int arr [ ] , int n ) { int diff ; for ( int i = 0 ; i < n - 1 ; i ++ ) { diff = abs ( arr [ i ] - arr [ i + 1 ] ) ; cout << diff << " β " ; } } int main ( ) { int arr [ ] = { 4 , 10 , 15 , 5 , 6 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; pairwiseDifference ( arr , n ) ; return 0 ; } |
Find the sum of all multiples of 2 and 5 below N | CPP program to find the sum of all multiples of 2 and 5 below N ; Function to find sum of AP series ; Number of terms ; Function to find the sum of all multiples of 2 and 5 below N ; Since , we need the sum of multiples less than N ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; long long sumAP ( long long n , long long d ) { n /= d ; return ( n ) * ( 1 + n ) * d / 2 ; } long long sumMultiples ( long long n ) { n -- ; return sumAP ( n , 2 ) + sumAP ( n , 5 ) - sumAP ( n , 10 ) ; } int main ( ) { long long n = 20 ; cout << sumMultiples ( n ) ; return 0 ; } |
Find the total marks obtained according to given marking scheme | C ++ implementation of above approach ; Function that calculates marks . ; for not attempt score + 0 ; for each correct answer score + 3 ; for each wrong answer score - 1 ; calculate total marks ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int markingScheme ( int N , int answerKey [ ] , int studentAnswer [ ] ) { int positive = 0 , negative = 0 , notattempt = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( studentAnswer [ i ] == 0 ) notattempt ++ ; else if ( answerKey [ i ] == studentAnswer [ i ] ) positive ++ ; else if ( answerKey [ i ] != studentAnswer [ i ] ) negative ++ ; } return ( positive * 3 ) + ( negative * -1 ) ; } int main ( ) { int answerKey [ ] = { 1 , 2 , 3 , 4 , 1 } ; int studentAnswer [ ] = { 1 , 2 , 3 , 4 , 0 } ; int N = sizeof ( answerKey ) / sizeof ( answerKey [ 0 ] ) ; cout << markingScheme ( N , answerKey , studentAnswer ) ; return 0 ; } |
Find the Product of first N Prime Numbers | C ++ implementation of above solution ; 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 ; Set all multiples of p to non - prime ; find the product of 1 st N prime numbers ; count of prime numbers ; product of prime numbers ; if the number is prime add it ; increase the count ; get to next number ; Driver code ; create the sieve ; find the value of 1 st n prime numbers | #include " cstring " NEW_LINE #include <iostream> NEW_LINE using namespace std ; #define MAX 10000 NEW_LINE bool prime [ MAX + 1 ] ; void SieveOfEratosthenes ( ) { memset ( prime , true , sizeof ( prime ) ) ; prime [ 1 ] = false ; for ( int p = 2 ; p * p <= MAX ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * 2 ; i <= MAX ; i += p ) prime [ i ] = false ; } } } int solve ( int n ) { int count = 0 , num = 1 ; long long int prod = 1 ; while ( count < n ) { if ( prime [ num ] ) { prod *= num ; count ++ ; } num ++ ; } return prod ; } int main ( ) { SieveOfEratosthenes ( ) ; int n = 5 ; cout << solve ( n ) ; return 0 ; } |
Program to find count of numbers having odd number of divisors in given range | C ++ implementation of the approach ; Function to return the count of divisors of a number ; Count the powers of the current prime i which divides a ; Update the count of divisors ; Reset the count ; If the remaining a is prime then a ^ 1 will be one of its prime factors ; Function to count numbers having odd number of divisors in range [ A , B ] ; To store the count of elements having odd number of divisors ; Iterate from a to b and find the count of their divisors ; To store the count of divisors of i ; If the divisor count of i is odd ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int divisor ( int a ) { int div = 1 , count = 0 ; for ( int i = 2 ; i <= sqrt ( a ) ; i ++ ) { while ( a % i == 0 ) { count ++ ; a = a / i ; } div = div * ( count + 1 ) ; count = 0 ; } if ( a > 1 ) { div = div * ( 2 ) ; } return div ; } int OddDivCount ( int a , int b ) { int res = 0 ; for ( int i = a ; i <= b ; ++ i ) { int divCount = divisor ( i ) ; if ( divCount % 2 ) { ++ res ; } } return res ; } int main ( ) { int a = 1 , b = 10 ; cout << OddDivCount ( a , b ) ; return 0 ; } |
Check if there is any pair in a given range with GCD is divisible by k | C ++ program to count the numbers divisible by k in a given range ; Returns count of numbers in [ l r ] that are divisible by k . ; Add 1 explicitly as l is divisible by k ; l is not divisible by k ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int Check_is_possible ( int l , int r , int k ) { int div_count = ( r / k ) - ( l / k ) ; if ( l % k == 0 ) div_count ++ ; return ( div_count > 1 ) ; } int main ( ) { int l = 30 , r = 70 , k = 10 ; if ( Check_is_possible ( l , r , k ) ) cout << " YES STRNEWLINE " ; else cout << " NO STRNEWLINE " ; return 0 ; } |
Find sum of N | C ++ program to find sum in Nth group ; calculate sum of Nth group ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int nth_group ( int n ) { return n * ( 2 * pow ( n , 2 ) + 1 ) ; } int main ( ) { int N = 5 ; cout << nth_group ( N ) ; return 0 ; } |
Find if a molecule can be formed from 3 atoms using their valence numbers | C ++ implementation of the above approach ; Function to check if it is possible ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printPossible ( int a , int b , int c ) { if ( ( a + b + c ) % 2 != 0 a + b < c ) cout << " NO " ; else cout << " YES " ; } int main ( ) { int a = 2 , b = 4 , c = 2 ; printPossible ( a , b , c ) ; return 0 ; } |
Check if a number is a Trojan Number | CPP program to check if a number is Trojan Number or not ; Function to check if a number can be expressed as x ^ y ; Try all numbers from 2 to sqrt ( n ) as base ; Keep increasing y while power ' p ' is smaller than n . ; Function to check if a number is Strong ; count the number for each prime factor ; minimum number of prime divisors should be 2 ; Function to check if a number is Trojan Number ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPerfectPower ( int n ) { if ( n == 1 ) return true ; for ( int x = 2 ; x <= sqrt ( n ) ; x ++ ) { int y = 2 ; int p = pow ( x , y ) ; while ( p <= n && p > 0 ) { if ( p == n ) return true ; y ++ ; p = pow ( x , y ) ; } } return false ; } bool isStrongNumber ( int n ) { unordered_map < int , int > count ; while ( n % 2 == 0 ) { n = n / 2 ; count [ 2 ] ++ ; } for ( int i = 3 ; i <= sqrt ( n ) ; i += 2 ) { while ( n % i == 0 ) { n = n / i ; count [ i ] ++ ; } } if ( n > 2 ) count [ n ] ++ ; int flag = 0 ; for ( auto b : count ) { if ( b . second == 1 ) { flag = 1 ; break ; } } if ( flag == 1 ) return false ; else return true ; } bool isTrojan ( int n ) { if ( ! isPerfectPower ( n ) && isStrongNumber ( n ) ) return true ; else return false ; } int main ( ) { int n = 108 ; if ( isTrojan ( n ) ) cout << " YES " ; else cout << " NO " ; return 0 ; } |
Find the sum of first N terms of the series 2 Γ β 3 + 4 Γ β 4 + 6 Γ β 5 + 8 Γ β 6 + ... | C ++ program to find sum upto N term of the series : 2 A 3 + 4 A 4 + 6 A 5 + 8 A 6 + ... ; calculate sum upto N term of series ; Driver code | #include <iostream> NEW_LINE using namespace std ; void Sum_upto_nth_Term ( int n ) { int r = n * ( n + 1 ) * ( 2 * n + 7 ) / 3 ; cout << r ; } int main ( ) { int N = 5 ; Sum_upto_nth_Term ( N ) ; return 0 ; } |
Absolute Difference between the Sum of Non | C ++ program to find the Absolute Difference between the Sum of Non - Prime numbers and Prime numbers of an Array ; Function to find the difference between the sum of non - primes and the sum of primes of an array . ; Find maximum value in the array ; USE SIEVE TO FIND ALL PRIME NUMBERS LESS THAN OR EQUAL TO max_val Create a boolean array " prime [ 0 . . n ] " . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; Remaining part of SIEVE ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; Store the sum of primes in S1 and the sum of non primes in S2 ; the number is prime ; the number is non - prime ; Return the absolute difference ; Driver Code ; Get the array ; Find the absolute difference | #include <bits/stdc++.h> NEW_LINE using namespace std ; int CalculateDifference ( int arr [ ] , int n ) { int max_val = * max_element ( arr , arr + n ) ; vector < bool > prime ( max_val + 1 , true ) ; prime [ 0 ] = false ; prime [ 1 ] = false ; for ( int p = 2 ; p * p <= max_val ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * 2 ; i <= max_val ; i += p ) prime [ i ] = false ; } } int S1 = 0 , S2 = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( prime [ arr [ i ] ] ) { S1 += arr [ i ] ; } else if ( arr [ i ] != 1 ) { S2 += arr [ i ] ; } } return abs ( S2 - S1 ) ; } int main ( ) { int arr [ ] = { 1 , 3 , 5 , 10 , 15 , 7 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << CalculateDifference ( arr , n ) ; return 0 ; } |
Program to find sum of 1 + x / 2 ! + x ^ 2 / 3 ! + ... + x ^ n / ( n + 1 ) ! | C ++ implementation of the approach ; Function to compute the series sum ; To store the value of S [ i - 1 ] ; Iterate over n to store sum in total ; Update previous with S [ i ] ; Driver code ; Get x and n ; Find and print the sum | #include <iostream> NEW_LINE using namespace std ; double sum ( int x , int n ) { double total = 1.0 ; double previous = 1.0 ; for ( int i = 1 ; i <= n ; i ++ ) { previous = ( previous * x ) / ( i + 1 ) ; total = total + previous ; } return total ; } int main ( ) { int x = 5 , n = 4 ; cout << " Sum β is : β " << sum ( x , n ) ; return 0 ; } |
Count number of integers less than or equal to N which has exactly 9 divisors | C ++ implementation of above approach ; Function to count factors in O ( N ) ; iterate and check if factor or not ; Function to count numbers having exactly 9 divisors ; check for all numbers <= N ; check if exactly 9 factors or not ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int numberOfDivisors ( int num ) { int c = 0 ; for ( int i = 1 ; i <= num ; i ++ ) { if ( num % i == 0 ) { c += 1 ; } } return c ; } int countNumbers ( int n ) { int c = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { if ( numberOfDivisors ( i ) == 9 ) c += 1 ; } return c ; } int main ( ) { int n = 1000 ; cout << countNumbers ( n ) ; return 0 ; } |
Number of distinct integers obtained by lcm ( X , N ) / X | C ++ program to find distinct integers ontained by lcm ( x , num ) / x ; Function to count the number of distinct integers ontained by lcm ( x , num ) / x ; iterate to count the number of factors ; Driver Code | #include <cmath> NEW_LINE #include <iostream> NEW_LINE using namespace std ; int numberOfDistinct ( int n ) { int ans = 0 ; for ( int i = 1 ; i <= sqrt ( n ) ; i ++ ) { if ( n % i == 0 ) { ans ++ ; if ( ( n / i ) != i ) ans ++ ; } } return ans ; } int main ( ) { int n = 3 ; cout << numberOfDistinct ( n ) ; return 0 ; } |
Ulam Number Sequence | CPP code to print nth Ulam number ; Array to store Ulam Number ; function to compute ulam Number ; push First 2 two term of the sequence in the array for further calculation ; loop to generate Ulam number ; traverse the array and check if i can be represented as sum of two distinct element of the array ; If count is 1 that means i can be represented as sum of two distinct terms of the sequence ; i is ulam number ; Driver code ; Pre compute Ulam Number sequence ; Print nth Ulam number | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 10000 NEW_LINE vector < int > arr ; void ulam ( ) { arr . push_back ( 1 ) ; arr . push_back ( 2 ) ; for ( int i = 3 ; i < MAX ; i ++ ) { int count = 0 ; for ( int j = 0 ; j < arr . size ( ) - 1 ; j ++ ) { for ( int k = j + 1 ; k < arr . size ( ) ; k ++ ) { if ( arr [ j ] + arr [ k ] == i ) { count ++ ; } if ( count > 1 ) break ; } if ( count > 1 ) break ; } if ( count == 1 ) { arr . push_back ( i ) ; } } } int main ( ) { ulam ( ) ; int n = 9 ; cout << arr [ n - 1 ] ; return 0 ; } |
Find the number of rectangles of size 2 * 1 which can be placed inside a rectangle of size n * m | CPP program to Find the number of rectangles of size 2 * 1 can be placed inside a rectangle of size n * m ; function to Find the number of rectangles of size 2 * 1 can be placed inside a rectangle of size n * m ; if n is even ; if m is even ; if both are odd ; Driver code ; function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int NumberOfRectangles ( int n , int m ) { if ( n % 2 == 0 ) return ( n / 2 ) * m ; else if ( m % 2 == 0 ) return ( m / 2 ) * n ; return ( n * m - 1 ) / 2 ; } int main ( ) { int n = 3 , m = 3 ; cout << NumberOfRectangles ( n , m ) ; return 0 ; } |
Next greater Number than N with the same quantity of digits A and B | C ++ program to find next greater Number than N with the same quantity of digits A and B ; Recursive function to find the required number ; If the resulting number is >= n and count of a = count of b , return the number ; select minimum of two and call the function again ; Function to find the number next greater Number than N with the same quantity of digits A and B ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; long findNumUtil ( long res , int a , int aCount , int b , int bCount , int n ) { if ( res > 1e11 ) return 1e11 ; if ( aCount == bCount && res >= n ) return res ; return min ( findNumUtil ( res * 10 + a , a , aCount + 1 , b , bCount , n ) , findNumUtil ( res * 10 + b , a , aCount , b , bCount + 1 , n ) ) ; } int findNum ( int n , int a , int b ) { int result = 0 ; int aCount = 0 ; int bCount = 0 ; return findNumUtil ( result , a , aCount , b , bCount , n ) ; } int main ( ) { int N = 4500 ; int A = 4 ; int B = 7 ; cout << findNum ( N , A , B ) ; return 0 ; } |
Minimum and maximum number of N chocolates after distribution among K students | CPP implementation of the above approach ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int main ( ) { int n = 7 , k = 3 ; if ( n % k == 0 ) cout << n / k << " β " << n / k ; else cout << ( ( n - ( n % k ) ) / k ) << " β " << ( ( ( n - ( n % k ) ) / k ) + 1 ) ; return 0 ; } |
Total money to be paid after traveling the given number of hours | CPP implementation of the above approach ; calculating hours travelled | #include <bits/stdc++.h> NEW_LINE using namespace std ; int main ( ) { float m = 50 , n = 5 , x = 67 , h = 2927 ; int z = ( ceil ( h / 60 * 1.0 ) ) ; if ( z <= n ) cout << z * m ; else cout << n * m + ( z - n ) * x ; return 0 ; } |