text
stringlengths
17
4.49k
code
stringlengths
49
5.46k
Check if the array has an element which is equal to product of remaining elements | C ++ implementation of the above approach ; Function to Check if the array has an element which is equal to product of all the remaining elements ; Calculate the product of all the elements ; Return true if any such element is found ; If no element is found ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool CheckArray ( int arr [ ] , int n ) { int prod = 1 ; for ( int i = 0 ; i < n ; ++ i ) prod *= arr [ i ] ; for ( int i = 0 ; i < n ; ++ i ) if ( arr [ i ] == prod / arr [ i ] ) return true ; return false ; } int main ( ) { int arr [ ] = { 1 , 2 , 12 , 3 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; if ( CheckArray ( arr , n ) ) cout << " YES " ; else cout << " NO " ; return 0 ; }
Sum of common divisors of two numbers A and B | C ++ implementation of above approach ; print the sum of common factors ; sum of common factors ; iterate from 1 to minimum of a and b ; if i is the common factor of both the numbers ; Driver code ; print the sum of common factors
#include <bits/stdc++.h> NEW_LINE using namespace std ; int sum ( int a , int b ) { int sum = 0 ; for ( int i = 1 ; i <= min ( a , b ) ; i ++ ) if ( a % i == 0 && b % i == 0 ) sum += i ; return sum ; } int main ( ) { int A = 10 , B = 15 ; cout << " Sum ▁ = ▁ " << sum ( A , B ) << endl ; return 0 ; }
Minimum number of cuts required to make circle segments equal sized | CPP program to find the minimum number of additional cuts required to make circle segments equal sized ; Function to find the minimum number of additional cuts required to make circle segments are equal sized ; Sort the array ; Initial gcd value ; Including the last segment ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minimumCuts ( int a [ ] , int n ) { sort ( a , a + n ) ; int gcd = a [ 1 ] - a [ 0 ] ; int s = gcd ; for ( int i = 2 ; i < n ; i ++ ) { gcd = __gcd ( gcd , a [ i ] - a [ i - 1 ] ) ; s += a [ i ] - a [ i - 1 ] ; } if ( 360 - s > 0 ) gcd = __gcd ( gcd , 360 - s ) ; return ( 360 / gcd ) - n ; } int main ( ) { int arr [ ] = { 30 , 60 , 180 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << minimumCuts ( arr , n ) ; return 0 ; }
Find a number that divides maximum array elements | CPP program to find a number that divides maximum array elements ; stores smallest prime factor for every number ; Calculating SPF ( Smallest Prime Factor ) for every number till MAXN . Time Complexity : O ( nloglogn ) ; marking smallest prime factor for every number to be itself . ; separately marking spf for every even number as 2 ; checking if i is prime ; marking SPF for all numbers divisible by i ; marking spf [ j ] if it is not previously marked ; A O ( log n ) function returning primefactorization by dividing by smallest prime factor at every step ; Function to find a number that divides maximum array elements ; precalculating Smallest Prime Factor ; Hash to store frequency of each divisors ; Traverse the array and get spf of each element ; calling getFactorization function ; Returns Set view ; Driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAXN 100001 NEW_LINE int spf [ MAXN ] ; void sieve ( ) { spf [ 1 ] = 1 ; for ( int i = 2 ; i < MAXN ; i ++ ) spf [ i ] = i ; for ( int i = 4 ; i < MAXN ; i += 2 ) spf [ i ] = 2 ; for ( int i = 3 ; i * i < MAXN ; i ++ ) { if ( spf [ i ] == i ) { for ( int j = i * i ; j < MAXN ; j += i ) if ( spf [ j ] == j ) spf [ j ] = i ; } } } vector < int > getFactorization ( int x ) { vector < int > ret ; while ( x != 1 ) { int temp = spf [ x ] ; ret . push_back ( temp ) ; while ( x % temp == 0 ) x = x / temp ; } return ret ; } int maxElement ( int A [ ] , int n ) { sieve ( ) ; map < int , int > m ; for ( int i = 0 ; i < n ; ++ i ) { vector < int > p = getFactorization ( A [ i ] ) ; for ( int i = 0 ; i < p . size ( ) ; i ++ ) m [ p [ i ] ] ++ ; } int cnt = 0 , ans = 1e+7 ; for ( auto i : m ) { if ( i . second >= cnt ) { cnt = i . second ; ans > i . first ? ans = i . first : ans = ans ; } } return ans ; } int main ( ) { int A [ ] = { 2 , 5 , 10 } ; int n = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << maxElement ( A , n ) ; return 0 ; }
Find Selling Price from given Profit Percentage and Cost | C ++ implementation of above approach ; Function to calculate the Selling Price ; Decimal Equivalent of Profit Percentage ; Find the Selling Price ; return the calculated Selling Price ; Driver code ; Get the CP and Profit % ; Printing the returned value
#include <iostream> NEW_LINE using namespace std ; float SellingPrice ( float CP , float PP ) { float P_decimal = 1 + ( PP / 100 ) ; float res = P_decimal * CP ; return res ; } int main ( ) { float C = 720 , P = 13 ; cout << SellingPrice ( C , P ) ; return 0 ; }
Sum and product of k smallest and k largest composite numbers in the array | C ++ program to find the sum and product of k smallest and k largest composite numbers in an array ; Create a boolean vector " prime [ 0 . . n ] " . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; Function that calculates the sum and product of k smallest and k largest composite numbers in an array ; Find maximum value in the array ; Use sieve to find all prime numbers less than or equal to max_val ; Set 0 and 1 as primes so that they don 't get counted as composite numbers ; Max Heap to store all the composite numbers ; Min Heap to store all the composite numbers ; Push all the composite numbers from the array to the heaps ; Calculate the products ; Calculate the sum ; Pop the current minimum element ; Pop the current maximum element ; Print results ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; vector < bool > SieveOfEratosthenes ( int max_val ) { vector < bool > prime ( max_val + 1 , true ) ; 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 ; } } return prime ; } void compositeSumAndProduct ( int arr [ ] , int n , int k ) { int max_val = * max_element ( arr , arr + n ) ; vector < bool > prime = SieveOfEratosthenes ( max_val ) ; prime [ 0 ] = true ; prime [ 1 ] = true ; priority_queue < int > maxHeap ; priority_queue < int , vector < int > , greater < int > > minHeap ; for ( int i = 0 ; i < n ; i ++ ) if ( ! prime [ arr [ i ] ] ) { minHeap . push ( arr [ i ] ) ; maxHeap . push ( arr [ i ] ) ; } long long int minProduct = 1 , maxProduct = 1 , minSum = 0 , maxSum = 0 ; while ( k -- ) { minProduct *= minHeap . top ( ) ; maxProduct *= maxHeap . top ( ) ; minSum += minHeap . top ( ) ; maxSum += maxHeap . top ( ) ; minHeap . pop ( ) ; maxHeap . pop ( ) ; } cout << " Sum ▁ of ▁ k - minimum ▁ composite ▁ numbers ▁ is ▁ " << minSum << " STRNEWLINE " ; cout << " Sum ▁ of ▁ k - maximum ▁ composite ▁ numbers ▁ is ▁ " << maxSum << " STRNEWLINE " ; cout << " Product ▁ of ▁ k - minimum ▁ composite ▁ numbers ▁ is ▁ " << minProduct << " STRNEWLINE " ; cout << " Product ▁ of ▁ k - maximum ▁ composite ▁ numbers ▁ is ▁ " << maxProduct ; } int main ( ) { int arr [ ] = { 4 , 2 , 12 , 13 , 5 , 19 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 3 ; compositeSumAndProduct ( arr , n , k ) ; return 0 ; }
Product of all the Composite Numbers in an array | C ++ program to find the product of all the composite numbers in an array ; Function that returns the the product of all composite numbers ; 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 . ; Set 0 and 1 as primes as they don 't need to be counted as composite numbers ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; Find the product of all composite numbers in the arr [ ] ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int compositeProduct ( int arr [ ] , int n ) { int max_val = * max_element ( arr , arr + n ) ; vector < bool > prime ( max_val + 1 , true ) ; prime [ 0 ] = true ; prime [ 1 ] = true ; 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 product = 1 ; for ( int i = 0 ; i < n ; i ++ ) if ( ! prime [ arr [ i ] ] ) { product *= arr [ i ] ; } return product ; } int main ( ) { int arr [ ] = { 2 , 3 , 4 , 5 , 6 , 7 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << compositeProduct ( arr , n ) ; return 0 ; }
Primality test for the sum of digits at odd places of a number | C ++ program to do Primality test for the sum of digits at odd places of a number ; Function that return sum of the digits at odd places ; Function that returns true if the number is prime else false ; Corner cases ; This condition is checked so that we can skip middle five numbers in the below loop ; Driver code ; Get the sum of the digits at odd places
#include <bits/stdc++.h> NEW_LINE using namespace std ; int sum_odd ( int n ) { int sum = 0 , pos = 1 ; while ( n ) { if ( pos % 2 == 1 ) sum += n % 10 ; n = n / 10 ; pos ++ ; } return sum ; } bool check_prime ( 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 ; } int main ( ) { int n = 223 ; int sum = sum_odd ( n ) ; if ( check_prime ( sum ) ) cout << " YES " << endl ; else cout << " NO " << endl ; return 0 ; }
Check if a number is a Mystery Number | C ++ implementation of above approach ; Finds reverse of given num x . ; if found print the pair , return
#include <bits/stdc++.h> NEW_LINE using namespace std ; int reverseNum ( int x ) { string s = to_string ( x ) ; reverse ( s . begin ( ) , s . end ( ) ) ; stringstream ss ( s ) ; int rev = 0 ; ss >> rev ; return rev ; } bool isMysteryNumber ( int n ) { for ( int i = 1 ; i <= n / 2 ; i ++ ) { int j = reverseNum ( i ) ; if ( i + j == n ) { cout << i << " ▁ " << j ; return true ; } } cout << " Not ▁ a ▁ Mystery ▁ Number " ; return false ; } int main ( ) { int n = 121 ; isMysteryNumber ( n ) ; return 0 ; }
Replace every element of the array by product of all other elements | C ++ program to Replace every element by the product of all other elements ; Calculate the product of all the elements ; Replace every element product of all other elements ; Driver code ; Print the modified array .
#include " iostream " NEW_LINE using namespace std ; void ReplaceElements ( int arr [ ] , int n ) { int prod = 1 ; for ( int i = 0 ; i < n ; ++ i ) { prod *= arr [ i ] ; } for ( int i = 0 ; i < n ; ++ i ) { arr [ i ] = prod / arr [ i ] ; } } int main ( ) { int arr [ ] = { 2 , 3 , 3 , 5 , 7 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; ReplaceElements ( arr , n ) ; for ( int i = 0 ; i < n ; ++ i ) { cout << arr [ i ] << " ▁ " ; } return 0 ; }
Check if there is any pair in a given range with GCD is divisible by k | ; function to count such possible numbers ; if i is divisible by k ; if count of such numbers is greater than one ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool Check_is_possible ( int l , int r , int k ) { int count = 0 ; for ( int i = l ; i <= r ; i ++ ) { if ( i % k == 0 ) count ++ ; } return ( count > 1 ) ; } int main ( ) { int l = 4 , r = 12 ; int k = 5 ; if ( Check_is_possible ( l , r , k ) ) cout << " YES STRNEWLINE " ; else cout << " NO STRNEWLINE " ; return 0 ; }
Check if any permutation of N equals any power of K | CPP implementation of above approach ; function to check if N and K are anagrams ; Function to check if any permutation of N exist such that it is some power of K ; generate all power of K under 10 ^ 18 ; check if any power of K is valid ; Driver program ; function call to print required answer
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isValid ( long long int N , long long int K ) { multiset < int > m1 , m2 ; while ( N > 0 ) { m1 . insert ( N % 10 ) ; N /= 10 ; } while ( K > 0 ) { m2 . insert ( K % 10 ) ; K /= 10 ; } if ( m1 == m2 ) return true ; return false ; } string anyPermutation ( long long int N , long long int K ) { long long int powK [ 100 ] , Limit = pow ( 10 , 18 ) ; powK [ 0 ] = K ; int i = 1 ; while ( powK [ i - 1 ] * K < Limit ) { powK [ i ] = powK [ i - 1 ] * K ; i ++ ; } for ( int j = 0 ; j < i ; j ++ ) if ( isValid ( N , powK [ j ] ) ) { return " True " ; } return " False " ; } int main ( ) { long long int N = 96889010407 , K = 7 ; cout << anyPermutation ( N , K ) ; return 0 ; }
Sum of first N natural numbers which are divisible by 2 and 7 | C ++ program to find sum of numbers from 1 to N which are divisible by 2 or 7 ; Function to calculate the sum of numbers divisible by 2 or 7 ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int sum ( int N ) { int S1 , S2 , S3 ; S1 = ( ( N / 2 ) ) * ( 2 * 2 + ( N / 2 - 1 ) * 2 ) / 2 ; S2 = ( ( N / 7 ) ) * ( 2 * 7 + ( N / 7 - 1 ) * 7 ) / 2 ; S3 = ( ( N / 14 ) ) * ( 2 * 14 + ( N / 14 - 1 ) * 14 ) / 2 ; return S1 + S2 - S3 ; } int main ( ) { int N = 20 ; cout << sum ( N ) ; return 0 ; }
Ways to color a skewed tree such that parent and child have different colors | C ++ program to count number of ways to color a N node skewed tree with k colors such that parent and children have different colors . ; fast_way is recursive method to calculate power ; driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int fastPow ( int N , int K ) { if ( K == 0 ) return 1 ; int temp = fastPow ( N , K / 2 ) ; if ( K % 2 == 0 ) return temp * temp ; else return N * temp * temp ; } int countWays ( int N , int K ) { return K * fastPow ( K - 1 , N - 1 ) ; } int main ( ) { int N = 3 , K = 3 ; cout << countWays ( N , K ) ; return 0 ; }
Sum of nth terms of Modified Fibonacci series made by every pair of two arrays | CPP program to find sum of n - th terms of a Fibonacci like series formed using first two terms of two arrays . ; if sum of first term is required ; if sum of second term is required ; fibonacci series used to find the nth term of every series ; as every b [ i ] term appears m times and every a [ i ] term also appears m times ; Driver code ; m is the size of the array
#include <bits/stdc++.h> NEW_LINE using namespace std ; int sumNth ( int A [ ] , int B [ ] , int m , int n ) { int res = 0 ; if ( n == 1 ) { for ( int i = 0 ; i < m ; i ++ ) res = res + A [ i ] ; } else if ( n == 2 ) { for ( int i = 0 ; i < m ; i ++ ) res = res + B [ i ] * m ; } else { int f [ n ] ; f [ 0 ] = 0 , f [ 1 ] = 1 ; for ( int i = 2 ; i < n ; i ++ ) f [ i ] = f [ i - 1 ] + f [ i - 2 ] ; for ( int i = 0 ; i < m ; i ++ ) { res = res + ( m * ( B [ i ] * f [ n - 1 ] ) ) + ( m * ( A [ i ] * f [ n - 2 ] ) ) ; } } return res ; } int main ( ) { int A [ ] = { 1 , 2 , 3 } ; int B [ ] = { 4 , 5 , 6 } ; int n = 3 ; int m = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << sumNth ( A , B , m , n ) ; return 0 ; }
Puzzle | Minimum distance for Lizard | CPP program to find minimum distance to be travlled by lizard . ; side of cube ; understand from diagram ; understand from diagram ; minimum distance
#include <bits/stdc++.h> NEW_LINE #define ll long long int NEW_LINE using namespace std ; int main ( ) { ll a = 5 ; ll AC = a ; ll CE = 2 * a ; double shortestDistace = sqrt ( AC * AC + CE * CE ) ; cout << shortestDistace << endl ; return 0 ; }
Find Sum of Series 1 ^ 2 | C ++ Program to find sum of series 1 ^ 2 - 2 ^ 2 + 3 ^ 3 - 4 ^ 4 + ... ; Function to find sum of series ; If n is even ; If n is odd ; return the result ; Driver Code ; Get n ; Find the sum ; Get n ; Find the sum
#include <bits/stdc++.h> NEW_LINE using namespace std ; int sum_of_series ( int n ) { int result = 0 ; if ( n % 2 == 0 ) { result = - ( n * ( n + 1 ) ) / 2 ; } else { result = ( n * ( n + 1 ) ) / 2 ; } return result ; } int main ( void ) { int n = 3 ; cout << sum_of_series ( n ) << endl ; n = 10 ; cout << sum_of_series ( n ) << endl ; }
Check whether the given numbers are Cousin prime or not | CPP program to check Cousin prime ; 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 ; Returns true if n1 and n2 are Cousin primes ; Check if they differ by 4 or not ; Check if both are prime number or not ; Driver code ; Get the 2 numbers ; Check the numbers for cousin prime
#include <bits/stdc++.h> 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 isCousinPrime ( int n1 , int n2 ) { if ( abs ( n1 - n2 ) != 4 ) return false ; else return ( isPrime ( n1 ) && isPrime ( n2 ) ) ; } int main ( ) { int n1 = 7 , n2 = 11 ; if ( isCousinPrime ( n1 , n2 ) ) cout << " YES " << endl ; else cout << " NO " << endl ; return 0 ; }
Chen Prime Number | CPP program to check Chen prime number ; Utility function to check whether number is semiprime or not ; Increment count of prime numbers ; If number is greater than 1 , add it to the count variable as it indicates the number remain is prime number ; Return '1' if count is equal to '2' else return '0' ; Utility function to check whether the given number is prime or not ; Corner cases ; This is checked so that we can skip middle five numbers in below loop ; Function to check Chen prime number ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int isSemiprime ( int num ) { int cnt = 0 ; for ( int i = 2 ; cnt < 2 && i * i <= num ; ++ i ) while ( num % i == 0 ) num /= I ; ++ cnt ; if ( num > 1 ) ++ cnt ; return cnt == 2 ; } 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 isChenPrime ( int n ) { if ( isPrime ( n ) && ( isSemiprime ( n + 2 ) || isPrime ( n + 2 ) ) ) return true ; else return false ; } int main ( ) { int n = 7 ; if ( isChenPrime ( n ) ) cout << " YES " ; else cout << " NO " ; return 0 ; }
Thabit number | CPP program to check if a given number is Thabit number or not . ; Utility function to check power of two ; function to check if the given number is Thabit Number ; Add 1 to the number ; Divide the number by 3 ; Check if the given number is power of 2 ; Driver Program ; Check if number is thabit number
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPowerOfTwo ( int n ) { return ( n && ! ( n & ( n - 1 ) ) ) ; } bool isThabitNumber ( int n ) { n = n + 1 ; if ( n % 3 == 0 ) n = n / 3 ; else return false ; if ( isPowerOfTwo ( n ) ) return true ; else return false ; } int main ( ) { int n = 47 ; if ( isThabitNumber ( n ) ) cout << " YES " ; else cout << " NO " ; return 0 ; }
Sum of all the prime numbers in a given range | C ++ Program to compute sum of prime number in a given range ; Suppose the constraint is N <= 1000 ; Declare an array for dynamic approach ; Method to compute the array ; Declare an extra array as arr ; Iterate the loop till sqrt ( n ) Time Complexity is O ( log ( n ) X sqrt ( n ) ) ; if ith element of arr is 0 i . e . marked as prime ; mark all of it 's multiples till N as non-prime by setting the locations to 1 ; Update the array ' dp ' with the running sum of prime numbers within the range [ 1 , N ] Time Complexity is O ( n ) ; Here , dp [ i ] is the sum of all the prime numbers within the range [ 1 , i ] ; Driver code ; Compute dp
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int N = 1000 ; int dp [ N + 1 ] ; void sieve ( ) { int arr [ N + 1 ] ; arr [ 0 ] = 1 ; arr [ 1 ] = 1 ; for ( int i = 2 ; i <= sqrt ( N ) ; i ++ ) if ( arr [ i ] == 0 ) for ( int j = i * i ; j <= N ; j += i ) arr [ j ] = 1 ; long runningPrimeSum = 0 ; for ( int i = 1 ; i <= N ; i ++ ) { if ( arr [ i ] == 0 ) runningPrimeSum += i ; dp [ i ] = runningPrimeSum ; } } int main ( ) { int l = 4 , r = 13 ; sieve ( ) ; cout << dp [ r ] - dp [ l - 1 ] ; return 0 ; }
Smallest Integer to be inserted to have equal sums | C ++ program to find the smallest number to be added to make the sum of left and right subarrays equal ; Function to find the minimum value to be added ; Variable to store entire array sum ; Variables to store sum of subarray1 and subarray 2 ; minimum value to be added ; Traverse through the array ; Sum of both halves ; Calculate minimum number to be added ; Driver code ; Length of array
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findMinEqualSums ( int a [ ] , int N ) { int sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { sum += a [ i ] ; } int sum1 = 0 , sum2 = 0 ; int min = INT_MAX ; for ( int i = 0 ; i < N ; i ++ ) { sum1 += a [ i ] ; sum2 = sum - sum1 ; if ( abs ( sum1 - sum2 ) < min ) { min = abs ( sum1 - sum2 ) ; } if ( min == 0 ) { break ; } } return min ; } int main ( ) { int a [ ] = { 3 , 2 , 1 , 5 , 7 , 8 } ; int N = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << ( findMinEqualSums ( a , N ) ) ; }
Sum of the 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 sum of 1 st N prime numbers ; count of prime numbers ; sum 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 <bits/stdc++.h> 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 sum = 0 ; while ( count < n ) { if ( prime [ num ] ) { sum += num ; count ++ ; } num ++ ; } return sum ; } int main ( ) { SieveOfEratosthenes ( ) ; int n = 4 ; cout << " Sum ▁ of ▁ 1st ▁ N ▁ prime ▁ numbers ▁ are ▁ : " << solve ( n ) ; return 0 ; }
Implementation of Wilson Primality test | C ++ implementation to check if a number is prime or not using Wilson Primality Test ; Function to calculate the factorial ; Function to check if the number is prime or not ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; long fact ( const int & p ) { if ( p <= 1 ) return 1 ; return p * fact ( p - 1 ) ; } bool isPrime ( const int & p ) { if ( p == 4 ) return false ; return bool ( fact ( p >> 1 ) % p ) ; } int main ( ) { cout << isPrime ( 127 ) ; return 0 ; }
Find the total Number of Digits in ( N ! ) N | C ++ program to find the total Number of Digits in ( N ! ) ^ N ; Function to find the total Number of Digits in ( N ! ) ^ N ; Finding X ; Calculating N * X ; Floor ( N * X ) + 1 return ceil ( sum ) ; equivalent to floor ( sum ) + 1 ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int CountDigits ( int n ) { if ( n == 1 ) return 1 ; double sum = 0 ; for ( int i = 2 ; i <= n ; ++ i ) { sum += ( double ) log ( i ) / ( double ) log ( 10 ) ; } sum *= ( double ) n ; } int main ( ) { int N = 5 ; cout << CountDigits ( N ) ; return 0 ; }
Find the value of max ( f ( x ) ) | C ++ implementation of above approach ; Function to calculate the value ; forming the prefix sum arrays ; Taking the query ; finding the sum in the range l to r in array a ; finding the sum in the range l to r in array b ; Finding the max value of the function ; Finding the min value of the function ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define ll long long NEW_LINE #define MAX 200006 NEW_LINE #define CONS 32766 NEW_LINE void calc ( ll a [ ] , ll b [ ] , ll lr [ ] , ll q , ll n ) { ll M , m , i , j , k , l , r , suma , sumb , cc ; cc = 0 ; for ( i = 0 ; i < n - 1 ; ++ i ) { a [ i + 1 ] += a [ i ] ; b [ i + 1 ] += b [ i ] ; } while ( q -- ) { l = lr [ cc ++ ] ; r = lr [ cc ++ ] ; l -= 2 ; r -= 1 ; suma = a [ r ] ; sumb = b [ r ] ; if ( l >= 0 ) { suma -= a [ l ] ; sumb -= b [ l ] ; } M = max ( CONS * suma + CONS * sumb , - CONS * suma - CONS * sumb ) ; M = max ( M , max ( CONS * suma - CONS * sumb , - CONS * suma + CONS * sumb ) ) ; m = min ( CONS * suma + CONS * sumb , - CONS * suma - CONS * sumb ) ; m = min ( m , min ( CONS * suma - CONS * sumb , - CONS * suma + CONS * sumb ) ) ; cout << ( M - m ) << " STRNEWLINE " ; } } int main ( ) { ll n = 5 , q = 2 ; ll a [ 5 ] = { 0 , 7 , 3 , 4 , 5 } ; ll b [ 5 ] = { 0 , 3 , 1 , 2 , 3 } ; ll lr [ q * 2 ] ; lr [ 0 ] = 1 ; lr [ 1 ] = 1 ; lr [ 2 ] = 1 ; lr [ 3 ] = 3 ; calc ( a , b , lr , q , n ) ; return 0 ; }
Program to find the Nth number of the series 2 , 10 , 24 , 44 , 70. ... . | CPP program to find the Nth term of the series 2 , 10 , 24 , 44 , 70. ... . ; function to return nth term of the series ; Driver code ; Get N ; Get Nth term
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define mod 1000000009 NEW_LINE int NthTerm ( long long n ) { long long x = ( 3 * n * n ) % mod ; return ( x - n + mod ) % mod ; } int main ( ) { long long N = 4 ; cout << NthTerm ( N ) ; return 0 ; }
Sum of first N natural numbers by taking powers of 2 as negative number | C ++ implementation of above approach ; to store power of 2 ; to store presum of the power of 2 's ; function to find power of 2 ; to store power of 2 ; to store pre sum ; Function to find the sum ; first store sum of first n natural numbers . ; find the first greater number than given number then minus double of this from answer ; Driver code ; function call ; function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int power [ 31 ] ; int pre [ 31 ] ; void PowerOfTwo ( ) { int x = 1 ; for ( int i = 0 ; i < 31 ; i ++ ) { power [ i ] = x ; x *= 2 ; } pre [ 0 ] = 1 ; for ( int i = 1 ; i < 31 ; i ++ ) pre [ i ] = pre [ i - 1 ] + power [ i ] ; } int Sum ( int n ) { int ans = n * ( n + 1 ) / 2 ; for ( int i = 0 ; i < 31 ; i ++ ) { if ( power [ i ] > n ) { ans -= 2 * pre [ i - 1 ] ; break ; } } return ans ; } int main ( ) { PowerOfTwo ( ) ; int n = 4 ; cout << Sum ( n ) ; return 0 ; }
Check if a number is Quartan Prime or not | CPP program to check if a number is Quartan 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 ; Driver Program ; Check if number is prime and of the form 16 * n + 1
#include <bits/stdc++.h> 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 ; } int main ( ) { int n = 17 ; if ( isPrime ( n ) && ( n % 16 == 1 ) ) { cout << " YES " ; } else { cout << " NO " ; } return 0 ; }
Print a number strictly less than a given number such that all its digits are distinct . | CPP program to find a number less than n such that all its digits are distinct ; Function to find a number less than n such that all its digits are distinct ; looping through numbers less than n ; initializing a hash array ; creating a copy of i ; initializing variables to compare lengths of digits ; counting frequency of the digits ; checking if each digit is present once ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findNumber ( int n ) { for ( int i = n - 1 ; > = 0 ; i -- ) { int count [ 10 ] = { 0 } ; int x = i ; int count1 = 0 , count2 = 0 ; while ( x ) { count [ x % 10 ] ++ ; x /= 10 ; count1 ++ ; } for ( int j = 0 ; j < 10 ; j ++ ) { if ( count [ j ] == 1 ) count2 ++ ; } if ( count1 == count2 ) return i ; } } int main ( ) { int n = 8490 ; cout << findNumber ( n ) ; return 0 ; }
Check if two Linked Lists are permutations of each other | C ++ program to check if linked lists are permutations of each other ; A linked list node ; Function to check if two linked lists * are permutations of each other * first : reference to head of first linked list * second : reference to head of second linked list ; Variables to keep track of sum and multiplication ; Traversing through linked list and calculating sum and multiply ; Traversing through linked list and calculating sum and multiply ; Function to add a node at the beginning of Linked List ; allocate node ; put in the data ; link the old list off the new node ; move the head to point to the new node ; Driver program to test above function ; First constructed linked list is : 12 -> 35 -> 1 -> 10 -> 34 -> 1 ; Second constructed linked list is : 35 -> 1 -> 12 -> 1 -> 10 -> 34
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * next ; } ; bool isPermutation ( struct Node * first , struct Node * second ) { int sum1 = 0 , sum2 = 0 , mul1 = 1 , mul2 = 1 ; struct Node * temp1 = first ; while ( temp1 != NULL ) { sum1 += temp1 -> data ; mul1 *= temp1 -> data ; temp1 = temp1 -> next ; } struct Node * temp2 = second ; while ( temp2 != NULL ) { sum2 += temp2 -> data ; mul2 *= temp2 -> data ; temp2 = temp2 -> next ; } return ( ( sum1 == sum2 ) && ( mul1 == mul2 ) ) ; } void push ( struct Node * * head_ref , int new_data ) { struct Node * new_node = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; new_node -> data = new_data ; new_node -> next = ( * head_ref ) ; ( * head_ref ) = new_node ; } int main ( ) { struct Node * first = NULL ; push ( & first , 1 ) ; push ( & first , 34 ) ; push ( & first , 10 ) ; push ( & first , 1 ) ; push ( & first , 35 ) ; push ( & first , 12 ) ; struct Node * second = NULL ; push ( & second , 35 ) ; push ( & second , 1 ) ; push ( & second , 12 ) ; push ( & second , 1 ) ; push ( & second , 10 ) ; push ( & second , 34 ) ; if ( isPermutation ( first , second ) ) { cout << " Yes " << endl ; } else { cout << " No " << endl ; } return 0 ; }
Find two distinct prime numbers with given product | C ++ program to find a distinct prime number pair whose product is equal to given number ; Function to generate all prime numbers less than n ; Initialize all entries of boolean array as true . A value in isPrime [ i ] will finally be false if i is Not a prime , else true bool isPrime [ n + 1 ] ; ; If isPrime [ p ] is not changed , then it is a prime ; Update all multiples of p ; Function to print a prime pair with given product ; Generating primes using Sieve ; Traversing all numbers to find first pair ; Driven Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool SieveOfEratosthenes ( int n , bool isPrime [ ] ) { isPrime [ 0 ] = isPrime [ 1 ] = false ; for ( int i = 2 ; i <= n ; i ++ ) isPrime [ i ] = true ; for ( int p = 2 ; p * p <= n ; p ++ ) { if ( isPrime [ p ] == true ) { for ( int i = p * 2 ; i <= n ; i += p ) isPrime [ i ] = false ; } } } void findPrimePair ( int n ) { int flag = 0 ; bool isPrime [ n + 1 ] ; SieveOfEratosthenes ( n , isPrime ) ; for ( int i = 2 ; i < n ; i ++ ) { int x = n / i ; if ( isPrime [ i ] && isPrime [ x ] and x != i and x * i == n ) { cout << i << " ▁ " << x ; flag = 1 ; return ; } } if ( ! flag ) cout << " No ▁ such ▁ pair ▁ found " ; } int main ( ) { int n = 39 ; findPrimePair ( n ) ; return 0 ; }
Program to find the common ratio of three numbers | C ++ implementation of above approach ; Function to print a : b : c ; To print the given proportion in simplest form . ; Driver code ; Get the ratios ; Get ratio a : b1 ; Get ratio b2 : c ; Find the ratio a : b : c
#include <bits/stdc++.h> NEW_LINE using namespace std ; void solveProportion ( int a , int b1 , int b2 , int c ) { int A = a * b2 ; int B = b1 * b2 ; int C = b1 * c ; int gcd = __gcd ( __gcd ( A , B ) , C ) ; cout << A / gcd << " : " << B / gcd << " : " << C / gcd ; } int main ( ) { int a , b1 , b2 , c ; a = 3 ; b1 = 4 ; b2 = 8 ; c = 9 ; solveProportion ( a , b1 , b2 , c ) ; return 0 ; }
Number of divisors of a given number N which are divisible by K | C ++ program to count number of divisors of N which are divisible by K ; Function to count number of divisors of N which are divisible by K ; Variable to store count of divisors ; Traverse from 1 to n ; increase the count if both the conditions are satisfied ; Driver code
#include <iostream> NEW_LINE using namespace std ; int countDivisors ( int n , int k ) { int count = 0 , i ; for ( i = 1 ; i <= n ; i ++ ) { if ( n % i == 0 && i % k == 0 ) { count ++ ; } } return count ; } int main ( ) { int n = 12 , k = 3 ; cout << countDivisors ( n , k ) ; return 0 ; }
Calculate volume and surface area of a cone | CPP program to calculate Volume and Surface area of Cone ; Function to calculate Volume of cone ; Function to calculate Surface area of cone ; Driver Code ; Printing value of volume and surface area
#include <iostream> NEW_LINE using namespace std ; float pi = 3.14159 ; float volume ( float r , float h ) { return ( float ( 1 ) / float ( 3 ) ) * pi * r * r * h ; } float surface_area ( float r , float s ) { return pi * r * s + pi * r * r ; } int main ( ) { float radius = 5 ; float slant_height = 13 ; float height = 12 ; float vol , sur_area ; cout << " Volume ▁ Of ▁ Cone ▁ : ▁ " << volume ( radius , height ) << endl ; cout << " Surface ▁ Area ▁ Of ▁ Cone ▁ : ▁ " << surface_area ( radius , slant_height ) ; return 0 ; }
Program to find the Nth term of the series 0 , 14 , 40 , 78 , 124 , ... | CPP program to find the N - th term of the series 0 , 14 , 40 , 78 , 124 . . . ; calculate sum upto Nth term of series ; return the final sum ; Driver code
#include <iostream> NEW_LINE #include <math.h> NEW_LINE using namespace std ; int nthTerm ( int n ) { return 6 * pow ( n , 2 ) - 4 * n - 2 ; } int main ( ) { int N = 4 ; cout << nthTerm ( N ) ; return 0 ; }
Program to find the Nth term of series 5 , 10 , 17 , 26 , 37 , 50 , 65 , 82 , ... | CPP program to find the N - th term of the series : 5 , 10 , 17 , 26 , 37 , 50 , 65 , 82 , ... ; calculate Nth term of series ; return the final sum ; Driver Function
#include <iostream> NEW_LINE #include <math.h> NEW_LINE using namespace std ; int nthTerm ( int n ) { return pow ( n , 2 ) + 2 * n + 2 ; } int main ( ) { int N = 4 ; cout << nthTerm ( N ) ; return 0 ; }
Find nth term of a given recurrence relation | C ++ program to find nth term of a given recurrence relation ; function to return required value ; Get the answer ; Return the answer ; Driver program ; Get the value of n ; function call to print result
#include <bits/stdc++.h> NEW_LINE using namespace std ; int sum ( int n ) { int ans = ( n * ( n - 1 ) ) / 2 ; return ans ; } int main ( ) { int n = 5 ; cout << sum ( n ) ; return 0 ; }
Program to find Nth term of the series 3 , 12 , 29 , 54 , 87 , ... | CPP program to find N - th term of the series : 3 , 12 , 29 , 54 , 87 , ... ; calculate Nth term of series ; Return Nth term ; driver code ; declaration of number of terms ; Get the Nth term
#include <iostream> NEW_LINE #include <math.h> NEW_LINE using namespace std ; int getNthTerm ( long long int N ) { return 4 * pow ( N , 2 ) - 3 * N + 2 ; } int main ( ) { long long int N = 10 ; cout << getNthTerm ( N ) ; return 0 ; }
Find sum of product of number in given series | C ++ program to find sum of product of number in given series ; function to calculate ( a ^ b ) % p ; Initialize result ; 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 return required answer ; modulo inverse of denominator ; calculating commentator part ; calculating t ! ; accumulating the final answer ; Driver code ; function call to print required sum
#include <bits/stdc++.h> NEW_LINE using namespace std ; typedef long long ll ; const long long MOD = 1000000007 ; ll power ( ll x , unsigned long long y , ll p ) { ll res = 1 ; x = x % p ; while ( y > 0 ) { if ( y & 1 ) res = ( res * x ) % p ; x = ( x * x ) % p ; } return res ; } ll sumProd ( ll n , ll t ) { ll dino = power ( t + 1 , MOD - 2 , MOD ) ; unsigned long long ans = 1 ; for ( ll i = n + t + 1 ; i > n ; -- i ) ans = ( ans % MOD * i % MOD ) % MOD ; ll tfact = 1 ; for ( int i = 1 ; i <= t ; ++ i ) tfact = ( tfact * i ) % MOD ; ans = ans * dino - tfact + MOD ; return ans % MOD ; } int main ( ) { ll n = 3 , t = 2 ; cout << sumProd ( n , t ) ; return 0 ; }
Find the sum of series 3 , 7 , 13 , 21 , 31. ... | C ++ Program to find the sum of given series ; Function to calculate sum ; Return sum ; Driver code
#include <iostream> NEW_LINE #include <math.h> NEW_LINE using namespace std ; int findSum ( int n ) { return ( n * ( pow ( n , 2 ) + 3 * n + 5 ) ) / 3 ; } int main ( ) { int n = 25 ; cout << findSum ( n ) ; return 0 ; }
Minimum Players required to win the game | C ++ program to find minimum players required to win the game anyhow ; function to calculate ( a ^ b ) % ( 10 ^ 9 + 7 ) . ; function to find the minimum required player ; computing the nenomenator ; computing modulo inverse of denominator ; final result ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define mod 1000000007 NEW_LINE long long int power ( long long int a , long long int b ) { long long int res = 1 ; while ( b ) { if ( b & 1 ) { res *= a ; res %= mod ; } b /= 2 ; a *= a ; a %= mod ; } return res ; } long long int minPlayer ( long long int n , long long int k ) { long long int num = ( ( power ( k , n ) - 1 ) + mod ) % mod ; long long int den = ( power ( k - 1 , mod - 2 ) + mod ) % mod ; long long int ans = ( ( ( num * den ) % mod ) * k ) % mod ; return ans ; } int main ( ) { long long int n = 3 , k = 3 ; cout << minPlayer ( n , k ) ; return 0 ; }
Sum of Factors of a Number using Prime Factorization | C ++ Program to find sum of all factors of a given number ; Using SieveOfEratosthenes to find smallest prime factor of all the numbers . For example , if N is 10 , s [ 2 ] = s [ 4 ] = s [ 6 ] = s [ 10 ] = 2 s [ 3 ] = s [ 9 ] = 3 s [ 5 ] = 5 s [ 7 ] = 7 ; Create a boolean array " prime [ 0 . . n ] " and initialize all entries in it as false . ; Initializing smallest factor equal to 2 for all the even numbers ; For odd numbers less then equal to n ; s ( i ) for a prime is the number itself ; For all multiples of current prime number ; i is the smallest prime factor for number " i * j " . ; Function to find sum of all prime factors ; Declaring array to store smallest prime factor of i at i - th index ; Filling values in s [ ] using sieve ; Current prime factor of N ; Power of current prime factor ; N is now N / s [ N ] . If new N als has smallest prime factor as currFactor , increment power ; Update current prime factor as s [ N ] and initializing power of factor as 1. ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void sieveOfEratosthenes ( int N , int s [ ] ) { vector < bool > prime ( N + 1 , false ) ; for ( int i = 2 ; i <= N ; i += 2 ) s [ i ] = 2 ; for ( int i = 3 ; i <= N ; i += 2 ) { if ( prime [ i ] == false ) { s [ i ] = i ; for ( int j = i ; j * i <= N ; j += 2 ) { if ( prime [ i * j ] == false ) { prime [ i * j ] = true ; s [ i * j ] = i ; } } } } } int findSum ( int N ) { int s [ N + 1 ] ; int ans = 1 ; sieveOfEratosthenes ( N , s ) ; int currFactor = s [ N ] ; int power = 1 ; while ( N > 1 ) { N /= s [ N ] ; if ( currFactor == s [ N ] ) { power ++ ; continue ; } int sum = 0 ; for ( int i = 0 ; i <= power ; i ++ ) sum += pow ( currFactor , i ) ; ans *= sum ; currFactor = s [ N ] ; power = 1 ; } return ans ; } int main ( ) { int n = 12 ; cout << " Sum ▁ of ▁ the ▁ factors ▁ is ▁ : ▁ " ; cout << findSum ( n ) ; return 0 ; }
Find Multiples of 2 or 3 or 5 less than or equal to N | CPP program to count number of multiples of 2 or 3 or 5 less than or equal to N ; Function to count number of multiples of 2 or 3 or 5 less than or equal to N ; As we have to check divisibility by three numbers , So we can implement bit masking ; we check whether jth bit is set or not , if jth bit is set , simply multiply to prod ; check for set bit ; check multiple of product ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countMultiples ( int n ) { int multiple [ ] = { 2 , 3 , 5 } ; int count = 0 , mask = pow ( 2 , 3 ) ; for ( int i = 1 ; i < mask ; i ++ ) { int prod = 1 ; for ( int j = 0 ; j < 3 ; j ++ ) { if ( i & 1 << j ) prod = prod * multiple [ j ] ; } if ( __builtin_popcount ( i ) % 2 == 1 ) count = count + n / prod ; else count = count - n / prod ; } return count ; } int main ( ) { int n = 10 ; cout << countMultiples ( n ) << endl ; return 0 ; }
Minimum value of N such that xor from 1 to N is equal to K | C ++ implementation of above approach ; Function to find the value of N ; variable to store the result ; handling case for '0' ; handling case for '1' ; when number is completely divided by 4 then minimum ' x ' will be ' k ' ; when number divided by 4 gives 3 as remainder then minimum ' x ' will be ' k - 1' ; else it is not possible to get k for any value of x ; Driver code ; let the given number be 7
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findN ( int k ) { int ans ; if ( k == 0 ) ans = 3 ; if ( k == 1 ) ans = 1 ; else if ( k % 4 == 0 ) ans = k ; else if ( k % 4 == 3 ) ans = k - 1 ; else ans = -1 ; return ans ; } int main ( ) { int k = 7 ; int res = findN ( k ) ; if ( res == -1 ) cout << " Not ▁ possible " ; else cout << res ; return 0 ; }
Permutations to arrange N persons around a circular table | C ++ code to demonstrate Circular Permutation ; Function to find no . of permutations ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int Circular ( int n ) { int Result = 1 ; while ( n > 0 ) { Result = Result * n ; n -- ; } return Result ; } int main ( ) { int n = 4 ; cout << Circular ( n - 1 ) ; }
Minimum time required to complete a work by N persons together | C ++ implementation of above approach ; Function to calculate the time ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; float calTime ( float arr [ ] , int n ) { float work = 0 ; for ( int i = 0 ; i < n ; i ++ ) work += 1 / arr [ i ] ; return 1 / work ; } int main ( ) { float arr [ ] = { 6.0 , 3.0 , 4.0 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << calTime ( arr , n ) << " ▁ Hours " ; return 0 ; }
Find the largest twins in given range | C ++ program to find the largest twin in given range ; Function to find twins ; Create a boolean array " prime [ 0 . . high ] " and initialize all entries it as true . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; Look for the smallest twin ; If p is not marked , then it is a prime ; Update all multiples of p ; Now print the largest twin in range ; Driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printTwins ( int low , int high ) { bool prime [ high + 1 ] , twin = false ; memset ( prime , true , sizeof ( prime ) ) ; prime [ 0 ] = prime [ 1 ] = false ; for ( int p = 2 ; p <= floor ( sqrt ( high ) ) + 1 ; p ++ ) { if ( prime [ p ] ) { for ( int i = p * 2 ; i <= high ; i += p ) prime [ i ] = false ; } } for ( int i = high ; i >= low ; i -- ) { if ( prime [ i ] && ( i - 2 >= low && prime [ i - 2 ] == true ) ) { cout << " Largest ▁ twins ▁ in ▁ given ▁ range : ▁ ( " << i - 2 << " , ▁ " << i << " ) " ; twin = true ; break ; } } if ( twin == false ) cout << " No ▁ such ▁ pair ▁ exists " << endl ; } int main ( ) { printTwins ( 10 , 100 ) ; return 0 ; }
Complement of a number with any base b | CPP program to find complement of a number with any base b ; Function to find ( b - 1 ) 's complement ; Calculate number of digits in the given number ; Largest digit in the number system with base b ; Largest number in the number system with base b ; return Complement ; Function to find b 's complement ; b ' s ▁ complement ▁ = ▁ ( b - 1 ) ' s complement + 1 ; Driver code
#include <iostream> NEW_LINE #include <cmath> NEW_LINE using namespace std ; int prevComplement ( int n , int b ) { int maxDigit , maxNum = 0 , digits = 0 , num = n ; while ( n != 0 ) { digits ++ ; n = n / 10 ; } maxDigit = b - 1 ; while ( digits -- ) { maxNum = maxNum * 10 + maxDigit ; } return maxNum - num ; } int complement ( int n , int b ) { return prevComplement ( n , b ) + 1 ; } int main ( ) { cout << prevComplement ( 25 , 7 ) << endl ; cout << complement ( 25 , 7 ) ; return 0 ; }
Minimum positive integer value possible of X for given A and B in X = P * A + Q * B | CPP Program to find minimum value of X in equation X = P * A + Q * B ; Utility function to calculate GCD ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int gcd ( int a , int b ) { if ( a == 0 ) return b ; return gcd ( b % a , a ) ; } int main ( ) { int a = 2 ; int b = 4 ; cout << gcd ( a , b ) ; return 0 ; }
Count elements in the given range which have maximum number of divisors | C ++ implementation of above approach ; Function to count the elements with maximum number of divisors ; to store number of divisors ; initialise with zero ; to store the maximum number of divisors ; to store required answer ; Find the first divisible number ; Count number of divisors ; Find number of elements with maximum number of divisors ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int MaximumDivisors ( int X , int Y ) { int arr [ Y - X + 1 ] ; memset ( arr , 0 , sizeof ( arr ) ) ; int mx = INT_MIN ; int cnt = 0 ; for ( int i = 1 ; i * i <= Y ; i ++ ) { int sq = i * i ; int first_divisible ; if ( ( X / i ) * i >= X ) first_divisible = ( X / i ) * i ; else first_divisible = ( X / i + 1 ) * i ; for ( int j = first_divisible ; j <= Y ; j += i ) { if ( j < sq ) continue ; else if ( j == sq ) arr [ j - X ] ++ ; else arr [ j - X ] += 2 ; } } for ( int i = X ; i <= Y ; i ++ ) { if ( arr [ i - X ] > mx ) { cnt = 1 ; mx = arr [ i - X ] ; } else if ( arr [ i - X ] == mx ) cnt ++ ; } return cnt ; } int main ( ) { int X = 1 , Y = 10 ; cout << MaximumDivisors ( X , Y ) << endl ; return 0 ; }
Find First element in AP which is multiple of given prime | ; Iterative Function to calculate ( x ^ y ) % p in O ( log y ) ; Initialize result ; 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 find nearest element in common ; base conditions ; Driver code ; module both A and D ; function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int power ( int x , int y , int p ) { int res = 1 ; x = x % p ; while ( y > 0 ) { if ( y & 1 ) res = ( res * x ) % p ; x = ( x * x ) % p ; } return res ; } int NearestElement ( int A , int D , int P ) { if ( A == 0 ) return 0 ; else if ( D == 0 ) return -1 ; else { int X = power ( D , P - 2 , P ) ; return ( X * ( P - A ) ) % P ; } } int main ( ) { int A = 4 , D = 9 , P = 11 ; A %= P ; D %= P ; cout << NearestElement ( A , D , P ) ; return 0 ; }
Cunningham chain | C ++ program for cunningham chain Function to print the series of first kind ; Function to print Cunningham chain of the first kind ; Iterate till all elements are printed ; check prime or not ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void print ( int p0 ) { int p1 , i = 0 , x , flag , k ; while ( 1 ) { flag = 1 ; x = ( int ) ( pow ( 2 , i ) ) ; p1 = x * p0 + ( x - 1 ) ; for ( k = 2 ; k < p1 ; k ++ ) { if ( p1 % k == 0 ) { flag = 0 ; break ; } } if ( flag == 0 ) break ; printf ( " % d ▁ " , p1 ) ; i ++ ; } } int main ( ) { int p0 = 2 ; print ( p0 ) ; return 0 ; }
Count pairs with Bitwise AND as ODD number | C ++ program to count pairs with AND giving a odd number ; Function to count number of odd pairs ; variable for counting odd pairs ; find all pairs ; find AND operation check odd or even ; return number of odd pair ; Driver Code ; calling function findOddPair and print number of odd pair
#include <iostream> NEW_LINE using namespace std ; int findOddPair ( int A [ ] , int N ) { int i , j ; int oddPair = 0 ; for ( i = 0 ; i < N ; i ++ ) { for ( j = i + 1 ; j < N ; j ++ ) { if ( ( A [ i ] & A [ j ] ) % 2 != 0 ) oddPair ++ ; } } return oddPair ; } int main ( ) { int a [ ] = { 5 , 1 , 3 , 2 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << findOddPair ( a , n ) << endl ; return 0 ; }
Sudo Placement [ 1.7 ] | Greatest Digital Root | C ++ program to print the digital roots of a number ; Function to return dig - sum ; Function to print the Digital Roots ; store the largest digital roots ; Iterate till sqrt ( n ) ; if i is a factor ; get the digit sum of both factors i and n / i ; if digit sum is greater then previous maximum ; if digit sum is greater then previous maximum ; if digit sum is same as then previous maximum , then check for larger divisor ; if digit sum is same as then previous maximum , then check for larger divisor ; Print the digital roots ; Driver Code ; Function call to print digital roots
#include <bits/stdc++.h> NEW_LINE using namespace std ; int summ ( int n ) { if ( n == 0 ) return 0 ; return ( n % 9 == 0 ) ? 9 : ( n % 9 ) ; } void printDigitalRoot ( int n ) { int maxi = 1 ; int dig = 1 ; for ( int i = 1 ; i <= sqrt ( n ) ; i ++ ) { if ( n % i == 0 ) { int d1 = summ ( n / i ) ; int d2 = summ ( i ) ; if ( d1 > maxi ) { dig = n / i ; maxi = d1 ; } if ( d2 > maxi ) { dig = i ; maxi = d2 ; } if ( d1 == maxi ) { if ( dig < ( n / i ) ) { dig = n / i ; maxi = d1 ; } } if ( d2 == maxi ) { if ( dig < i ) { dig = i ; maxi = d2 ; } } } } cout << dig << " ▁ " << maxi << endl ; } int main ( ) { int n = 10 ; printDigitalRoot ( n ) ; return 0 ; }
Sum of all elements up to Nth row in a Pascal triangle | C ++ program to find sum of all elements upto nth row in Pascal triangle . ; Function to find sum of all elements upto nth row . ; Initialize sum with 0 ; Calculate 2 ^ n ; Driver function
#include <bits/stdc++.h> NEW_LINE using namespace std ; long long int calculateSum ( int n ) { long long int sum = 0 ; sum = 1 << n ; return ( sum - 1 ) ; } int main ( ) { int n = 10 ; cout << " ▁ Sum ▁ of ▁ all ▁ elements : " << calculateSum ( n ) ; return 0 ; }
Divide two integers without using multiplication , division and mod operator | Set2 | C ++ program for above approach ; Returns the quotient of dividend / divisor . ; Calculate sign of divisor i . e . , sign will be negative only if either one of them is negative otherwise it will be positive ; Remove signs of dividend and divisor ; Zero division Exception . ; Using Formula derived above . ; Drivers code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void Divide ( int a , int b ) { long long dividend = ( long long ) a ; long long divisor = ( long long ) b ; long long sign = ( dividend < 0 ) ^ ( divisor < 0 ) ? -1 : 1 ; dividend = abs ( dividend ) ; divisor = abs ( divisor ) ; if ( divisor == 0 ) { cout << " Cannot ▁ Divide ▁ by ▁ 0" << endl ; return ; } if ( dividend == 0 ) { cout << a << " ▁ / ▁ " << b << " ▁ is ▁ equal ▁ to ▁ : ▁ " << 0 << endl ; return ; } if ( divisor == 1 ) { cout << a << " ▁ / ▁ " << b << " ▁ is ▁ equal ▁ to ▁ : ▁ " << sign * dividend << endl ; return ; } cout << a << " ▁ / ▁ " << b << " ▁ is ▁ equal ▁ to ▁ : ▁ " << sign * exp ( log ( dividend ) - log ( divisor ) ) << endl ; } int main ( ) { int a = 10 , b = 5 ; Divide ( a , b ) ; a = 49 , b = -7 ; Divide ( a , b ) ; return 0 ; }
Represent the fraction of two numbers in the string format | C ++ program to calculate fraction of two numbers ; Function to return the required fraction in string format ; If the numerator is zero , answer is 0 ; If any one ( out of numerator and denominator ) is - ve , sign of resultant answer - ve . ; Calculate the absolute part ( before decimal point ) . ; Output string to store the answer ; Append sign ; Append the initial part ; If completely divisible , return answer . ; Initialize Remainder ; Position at which fraction starts repeating if it exists ; If this remainder is already seen , then there exists a repeating fraction . ; Index to insert parentheses ; Calculate quotient , append it to result and calculate next remainder ; If repeating fraction exists , insert parentheses . ; Return result . ; Drivers Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string calculateFraction ( int num , int den ) { if ( num == 0 ) return "0" ; int sign = ( num < 0 ) ^ ( den < 0 ) ? -1 : 1 ; num = abs ( num ) ; den = abs ( den ) ; int initial = num / den ; string res ; if ( sign == -1 ) res += " - " ; res += to_string ( initial ) ; if ( num % den == 0 ) return res ; res += " . " ; int rem = num % den ; map < int , int > mp ; int index ; bool repeating = false ; while ( rem > 0 && ! repeating ) { if ( mp . find ( rem ) != mp . end ( ) ) { index = mp [ rem ] ; repeating = true ; break ; } else mp [ rem ] = res . size ( ) ; rem = rem * 10 ; int temp = rem / den ; res += to_string ( temp ) ; rem = rem % den ; } if ( repeating ) { res += " ) " ; res . insert ( index , " ( " ) ; } return res ; } int main ( ) { int num = 50 , den = 22 ; cout << calculateFraction ( num , den ) << endl ; num = -1 , den = 2 ; cout << calculateFraction ( num , den ) << endl ; return 0 ; }
Check if the n | CPP Program to check if the nth is odd or even in a sequence where each term is sum of previous two term ; Return if the nth term is even or odd . ; If a is even ; If b is even ; If b is odd ; If a is odd ; If b is odd ; If b is eve ; Driven Program
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool findNature ( int a , int b , int n ) { if ( n == 0 ) return ( a & 1 ) ; if ( n == 1 ) return ( b & 1 ) ; if ( ! ( a & 1 ) ) { if ( ! ( b & 1 ) ) return false ; else return ( n % 3 != 0 ) ; } else { if ( ! ( b & 1 ) ) return ( ( n - 1 ) % 3 != 0 ) ; else return ( ( n + 1 ) % 3 != 0 ) ; } } int main ( ) { int a = 2 , b = 4 ; int n = 3 ; ( findNature ( a , b , n ) ? ( cout << " Odd " << " ▁ " ) : ( cout << " Even " << " ▁ " ) ) ; return 0 ; }
Check if mirror image of a number is same if displayed in seven segment display | C ++ Program to check if mirror image of a number is same if displayed in seven segment display ; Return " Yes " , if the mirror image of number is same as the given number Else return " No " ; Checking if the number contain only 0 , 1 , 8. ; Checking if the number is palindrome or not . ; If corresponding index is not equal . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string checkEqual ( string S ) { for ( int i = 0 ; i < S . size ( ) ; i ++ ) { if ( S [ i ] != '1' && S [ i ] != '0' && S [ i ] != '8' ) { return " No " ; } } int start = 0 , end = S . size ( ) - 1 ; while ( start < end ) { if ( S [ start ] != S [ end ] ) { return " No " ; } start ++ ; end -- ; } return " Yes " ; } int main ( ) { string S = "101" ; cout << checkEqual ( S ) << endl ; return 0 ; }
Check whether a given number is Polydivisible or Not | CPP program to check whether a number is polydivisible or not ; function to check polydivisible number ; digit extraction of input number ; store the digits in an array ; n contains first i digits ; n should be divisible by i ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void check_polydivisible ( int n ) { int N = n ; vector < int > digit ; while ( n > 0 ) { digit . push_back ( n % 10 ) ; n /= 10 ; } reverse ( digit . begin ( ) , digit . end ( ) ) ; bool flag = true ; n = digit [ 0 ] ; for ( int i = 1 ; i < digit . size ( ) ; i ++ ) { n = n * 10 + digit [ i ] ; if ( n % ( i + 1 ) != 0 ) { flag = false ; break ; } } if ( flag ) cout << N << " ▁ is ▁ Polydivisible ▁ number . " ; else cout << N << " ▁ is ▁ Not ▁ Polydivisible ▁ number . " ; } int main ( ) { int n = 345654 ; check_polydivisible ( n ) ; }
Check if given number is a power of d where d is a power of 2 | CPP program to find if a number is power of d where d is power of 2. ; Function to count the number of ways to paint N * 3 grid based on given conditions ; Check if there is only one bit set in n ; count 0 bits before set bit ; If count is a multiple of log2 ( d ) then return true else false ; If there are more than 1 bit set then n is not a power of 4 ; Driver program to test above function
#include <stdio.h> NEW_LINE unsigned int Log2n ( unsigned int n ) { return ( n > 1 ) ? 1 + Log2n ( n / 2 ) : 0 ; } bool isPowerOfd ( unsigned int n , unsigned int d ) { int count = 0 ; if ( n && ! ( n & ( n - 1 ) ) ) { while ( n > 1 ) { n >>= 1 ; count += 1 ; } return ( count % ( Log2n ( d ) ) == 0 ) ; } return false ; } int main ( ) { int n = 64 , d = 8 ; if ( isPowerOfd ( n , d ) ) printf ( " % d ▁ is ▁ a ▁ power ▁ of ▁ % d " , n , d ) ; else printf ( " % d ▁ is ▁ not ▁ a ▁ power ▁ of ▁ % d " , n , d ) ; return 0 ; }
Total nodes traversed in Euler Tour Tree | C ++ program to check the number of nodes in Euler Tour tree . ; Adjacency list representation of tree ; Function to add edges to tree ; Program to check if calculated Value is equal to 2 * size - 1 ; Add out - degree of each node ; Driver code ; Constructing 1 st tree from example ; Out_deg [ node [ i ] ] is equal to adj [ i ] . size ( ) ; clear previous stored tree ; Constructing 2 nd tree from example ; Out_deg [ node [ i ] ] is equal to adj [ i ] . size ( )
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 1001 NEW_LINE vector < int > adj [ MAX ] ; void add_edge ( int u , int v ) { adj [ u ] . push_back ( v ) ; } void checkTotalNumberofNodes ( int actualAnswer , int size ) { int calculatedAnswer = size ; for ( int i = 1 ; i <= size ; i ++ ) calculatedAnswer += adj [ i ] . size ( ) ; if ( actualAnswer == calculatedAnswer ) cout << " Calculated ▁ Answer ▁ is ▁ " << calculatedAnswer << " ▁ and ▁ is ▁ Equal ▁ to ▁ Actual ▁ Answer STRNEWLINE " ; else cout << " Calculated ▁ Answer ▁ is ▁ Incorrect STRNEWLINE " ; } int main ( ) { int N = 8 ; add_edge ( 1 , 2 ) ; add_edge ( 1 , 3 ) ; add_edge ( 2 , 4 ) ; add_edge ( 2 , 5 ) ; add_edge ( 3 , 6 ) ; add_edge ( 3 , 7 ) ; add_edge ( 6 , 8 ) ; checkTotalNumberofNodes ( 2 * N - 1 , N ) ; for ( int i = 1 ; i <= N ; i ++ ) adj [ i ] . clear ( ) ; N = 9 ; add_edge ( 1 , 2 ) ; add_edge ( 1 , 3 ) ; add_edge ( 2 , 4 ) ; add_edge ( 2 , 5 ) ; add_edge ( 2 , 6 ) ; add_edge ( 3 , 9 ) ; add_edge ( 5 , 7 ) ; add_edge ( 5 , 8 ) ; checkTotalNumberofNodes ( 2 * N - 1 , N ) ; return 0 ; }
Octahedral Number | C ++ program to find nth octahedral number ; Function to find octahedral number ; Formula to calculate nth octahedral number ; Drivers code ; print result
#include <bits/stdc++.h> NEW_LINE using namespace std ; int octahedral_num ( int n ) { return n * ( 2 * n * n + 1 ) / 3 ; } int main ( ) { int n = 5 ; cout << n << " th ▁ Octahedral ▁ number : ▁ " ; cout << octahedral_num ( n ) ; return 0 ; }
Centered tetrahedral number | C ++ Program to find nth Centered tetrahedral number ; Function to find centered Centered tetrahedral number ; Formula to calculate nth Centered tetrahedral number and return it into main function . ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int centeredTetrahedralNumber ( int n ) { return ( 2 * n + 1 ) * ( n * n + n + 3 ) / 3 ; } int main ( ) { int n = 6 ; cout << centeredTetrahedralNumber ( n ) ; return 0 ; }
Swapping four variables without temporary variable | CPP program to swap 4 variables without using temporary variable . ; swapping a and b variables ; swapping b and c variables ; swapping c and d variables ; Driver code ; initialising variables ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void swap ( int a , int b , int c , int d ) { a = a + b ; b = a - b ; a = a - b ; b = b + c ; c = b - c ; b = b - c ; c = c + d ; d = c - d ; c = c - d ; cout << " values ▁ after ▁ swapping ▁ are ▁ : ▁ " << endl ; cout << " a ▁ = ▁ " << a << endl ; cout << " b ▁ = ▁ " << b << endl ; cout << " c ▁ = ▁ " << c << endl ; cout << " d ▁ = ▁ " << d << endl ; } int main ( ) { int a = 1 ; int b = 2 ; int c = 3 ; int d = 4 ; cout << " Values ▁ before ▁ swapping ▁ are ▁ : " << endl ; cout << " a ▁ = ▁ " << a << endl ; cout << " b ▁ = ▁ " << b << endl ; cout << " c ▁ = ▁ " << c << endl ; cout << " d ▁ = ▁ " << d << endl << endl ; swap ( a , b , c , d ) ; return 0 ; }
Sum of first n natural numbers | CPP program to find sum series 1 , 3 , 6 , 10 , 15 , 21. . . and then find its sum ; Function to find the sum of series ; Driver code
#include <iostream> NEW_LINE using namespace std ; int seriesSum ( int n ) { int sum = 0 ; for ( int i = 1 ; i <= n ; i ++ ) sum += i * ( i + 1 ) / 2 ; return sum ; } int main ( ) { int n = 4 ; cout << seriesSum ( n ) ; return 0 ; }
Centrosymmetric Matrix | CPP Program to check whether given matrix is centrosymmetric or not . ; Finding the middle row of the matrix ; for each row upto middle row . ; If each element and its corresponding element is not equal then return false . ; Driven Program
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 3 NEW_LINE bool checkCentrosymmetricted ( int n , int m [ N ] [ N ] ) { int mid_row ; if ( n & 1 ) mid_row = n / 2 + 1 ; else mid_row = n / 2 ; for ( int i = 0 ; i < mid_row ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { if ( m [ i ] [ j ] != m [ n - i - 1 ] [ n - j - 1 ] ) return false ; } } return true ; } int main ( ) { int n = 3 ; int m [ N ] [ N ] = { { 1 , 3 , 5 } , { 6 , 8 , 6 } , { 5 , 3 , 1 } } ; ( checkCentrosymmetricted ( n , m ) ? ( cout << " Yes " ) : ( cout << " No " ) ) ; return 0 ; }
Centered triangular number | C ++ Program to find the nth Centered Triangular number ; function for Centered Triangular number ; formula for find Centered Triangular number nth term ; Driver Code ; For 3 rd Centered Triangular number ; For 12 th Centered Triangular number
#include <iostream> NEW_LINE using namespace std ; int Centered_Triangular_num ( int n ) { return ( 3 * n * n + 3 * n + 2 ) / 2 ; } int main ( ) { int n = 3 ; cout << Centered_Triangular_num ( n ) << endl ; n = 12 ; cout << Centered_Triangular_num ( n ) << endl ; return 0 ; }
Array with GCD of any of its subset belongs to the given array | C ++ implementation to generate the required array ; Function to return gcd of a and b ; Function to find gcd of array of numbers ; Function to generate the array with required constraints . ; computing GCD of the given set ; Solution exists if GCD of array is equal to the minimum element of the array ; Printing the built array ; Driver function ; Taking in the input and initializing the set STL set in cpp has a property that it maintains the elements in sorted order , thus we do not need to sort them externally ; Calling the computing 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 findGCD ( vector < int > arr , int n ) { int result = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) result = gcd ( arr [ i ] , result ) ; return result ; } void compute ( vector < int > arr , int n ) { vector < int > answer ; int GCD_of_array = findGCD ( arr , n ) ; if ( GCD_of_array == arr [ 0 ] ) { answer . push_back ( arr [ 0 ] ) ; for ( int i = 1 ; i < n ; i ++ ) { answer . push_back ( arr [ 0 ] ) ; answer . push_back ( arr [ i ] ) ; } for ( int i = 0 ; i < answer . size ( ) ; i ++ ) cout << answer [ i ] << " ▁ " ; } else cout << " No ▁ array ▁ can ▁ be ▁ build " ; } int main ( ) { int n = 3 ; int input [ ] = { 2 , 5 , 6 , 7 , 11 } ; set < int > GCD ( input , input + n ) ; vector < int > arr ; set < int > :: iterator it ; for ( it = GCD . begin ( ) ; it != GCD . end ( ) ; ++ it ) arr . push_back ( * it ) ; compute ( arr , n ) ; return 0 ; }
Combinatorics on ordered trees | C ++ code to find the number of ordered trees with given number of edges and leaves ; Function returns value of Binomial Coefficient C ( n , k ) ; Calculate value of Binomial Coefficient in bottom up manner ; Base Cases ; Calculate value using previously stored values ; Function to calculate the number of trees with exactly k leaves . ; Function to calculate total number of nodes of degree d in these trees . ; Function to calculate the number of trees in which the root has degree r . ; Driver program to test above functions ; Number of trees having 3 edges and exactly 2 leaves ; Number of nodes of degree 3 in a tree having 4 edges ; Number of trees having 3 edges where root has degree 2
#include <bits/stdc++.h> NEW_LINE using namespace std ; int binomialCoeff ( int n , int k ) { int C [ n + 1 ] [ k + 1 ] = { 0 } ; int i , j ; for ( i = 0 ; i <= n ; i ++ ) { for ( j = 0 ; j <= min ( i , k ) ; j ++ ) { if ( j == 0 j == i ) C [ i ] [ j ] = 1 ; else C [ i ] [ j ] = C [ i - 1 ] [ j - 1 ] + C [ i - 1 ] [ j ] ; } } return C [ n ] [ k ] ; } int k_Leaves ( int n , int k ) { int ans = ( binomialCoeff ( n , k ) * binomialCoeff ( n , k - 1 ) ) / n ; cout << " Number ▁ of ▁ trees ▁ having ▁ 4 ▁ edges " << " ▁ and ▁ exactly ▁ 2 ▁ leaves ▁ : ▁ " << ans << endl ; return 0 ; } int numberOfNodes ( int n , int d ) { int ans = binomialCoeff ( 2 * n - 1 - d , n - 1 ) ; cout << " Number ▁ of ▁ nodes ▁ of ▁ degree ▁ 1 ▁ in " << " ▁ a ▁ tree ▁ having ▁ 4 ▁ edges ▁ : ▁ " << ans << endl ; return 0 ; } int rootDegreeR ( int n , int r ) { int ans = r * binomialCoeff ( 2 * n - 1 - r , n - 1 ) ; ans = ans / n ; cout << " Number ▁ of ▁ trees ▁ having ▁ 4 ▁ edges " << " ▁ where ▁ root ▁ has ▁ degree ▁ 2 ▁ : ▁ " << ans << endl ; return 0 ; } int main ( ) { k_Leaves ( 3 , 2 ) ; numberOfNodes ( 3 , 1 ) ; rootDegreeR ( 3 , 2 ) ; return 0 ; }
Repeated Unit Divisibility | CPP program to find least value of k for which R ( k ) is divisible by n ; To find least value of k ; To check n is coprime or not ; to store R ( k ) mod n and 10 ^ k mod n value ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int repUnitValue ( int n ) { if ( n % 2 == 0 n % 5 == 0 ) return 0 ; int rem = 1 ; int power = 1 ; int k = 1 ; while ( rem % n != 0 ) { k ++ ; power = power * 10 % n ; rem = ( rem + power ) % n ; } return k ; } int main ( ) { int n = 13 ; cout << repUnitValue ( n ) ; return 0 ; }
First N natural can be divided into two sets with given difference and co | CPP code to determine whether numbers 1 to N can be divided into two sets such that absolute difference between sum of these two sets is M and these two sum are co - prime ; function that returns boolean value on the basis of whether it is possible to divide 1 to N numbers into two sets that satisfy given conditions . ; initializing total sum of 1 to n numbers ; since ( 1 ) total_sum = sum_s1 + sum_s2 and ( 2 ) m = sum_s1 - sum_s2 assuming sum_s1 > sum_s2 . solving these 2 equations to get sum_s1 and sum_s2 ; total_sum = sum_s1 + sum_s2 and therefore ; if total sum is less than the absolute difference then there is no way we can split n numbers into two sets so return false ; check if these two sums are integers and they add up to total sum and also if their absolute difference is m . ; Now if two sum are co - prime then return true , else return false . ; if two sums don 't add up to total sum or if their absolute difference is not m, then there is no way to split n numbers, hence return false ; Driver code ; function call to determine answer
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isSplittable ( int n , int m ) { int total_sum = ( n * ( n + 1 ) ) / 2 ; int sum_s1 = ( total_sum + m ) / 2 ; int sum_s2 = total_sum - sum_s1 ; if ( total_sum < m ) return false ; if ( sum_s1 + sum_s2 == total_sum && sum_s1 - sum_s2 == m ) return ( __gcd ( sum_s1 , sum_s2 ) == 1 ) ; return false ; } int main ( ) { int n = 5 , m = 7 ; if ( isSplittable ( n , m ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Making zero array by decrementing pairs of adjacent | CPP implementation of the above approach ; converting array element into number ; Check if divisible by 11 ; Driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPossibleToZero ( int a [ ] , int n ) { int num = 0 ; for ( int i = 0 ; i < n ; i ++ ) num = num * 10 + a [ i ] ; return ( num % 11 == 0 ) ; } int main ( ) { int arr [ ] = { 0 , 1 , 1 , 0 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; if ( isPossibleToZero ( arr , n ) ) cout << " YES " ; else cout << " NO " ; }
Blum Integer | CPP program to check if a number is a Blum integer ; Function to cheek if number is Blum Integer ; to store prime numbers from 2 to n ; If prime [ i ] is not changed , then it is a prime ; Update all multiples of p ; to check if the given odd integer is Blum Integer or not ; checking the factors are of 4 t + 3 form or not ; driver code ; give odd integer greater than 20
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isBlumInteger ( 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 ; } } for ( int i = 2 ; i <= n ; i ++ ) { if ( prime [ i ] ) { if ( ( n % i == 0 ) && ( ( i - 3 ) % 4 ) == 0 ) { int q = n / i ; return ( q != i && prime [ q ] && ( q - 3 ) % 4 == 0 ) ; } } } return false ; } int main ( ) { int n = 249 ; if ( isBlumInteger ( n ) ) cout << " Yes " ; else cout << " No " ; }
Program to calculate value of nCr | CPP program To calculate The Value Of nCr ; Returns factorial of n ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int fact ( int n ) ; int nCr ( int n , int r ) { return fact ( n ) / ( fact ( r ) * fact ( n - r ) ) ; } int fact ( int n ) { int res = 1 ; for ( int i = 2 ; i <= n ; i ++ ) res = res * i ; return res ; } int main ( ) { int n = 5 , r = 3 ; cout << nCr ( n , r ) ; return 0 ; }
Program to print the sum of the given nth term | CPP program to illustrate ... Summation of series ; function to calculate sum of series ; Sum of n terms is n ^ 2 ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int summingSeries ( long n ) { return pow ( n , 2 ) ; } int main ( ) { int n = 100 ; cout << " The ▁ sum ▁ of ▁ n ▁ term ▁ is : ▁ " << summingSeries ( n ) << endl ; return 0 ; }
Brahmagupta Fibonacci Identity | CPP code to verify Brahmagupta Fibonacci identity ; represent the product as sum of 2 squares ; check identity criteria ; Driver code ; 1 ^ 2 + 2 ^ 2 ; 3 ^ 2 + 4 ^ 2 ; express product of sum of 2 squares as sum of ( sum of 2 squares )
#include <bits/stdc++.h> NEW_LINE using namespace std ; void find_sum_of_two_squares ( int a , int b ) { int ab = a * b ; for ( int i = 0 ; i * i <= ab ; i ++ ) { for ( int j = i ; i * i + j * j <= ab ; j ++ ) { if ( i * i + j * j == ab ) cout << i << " ^ 2 ▁ + ▁ " << j << " ^ 2 ▁ = ▁ " << ab << " STRNEWLINE " ; } } } int main ( ) { int a = 1 * 1 + 2 * 2 ; int b = 3 * 3 + 4 * 4 ; cout << " Representation ▁ of ▁ a ▁ * ▁ b ▁ as ▁ sum " " ▁ of ▁ 2 ▁ squares : STRNEWLINE " ; find_sum_of_two_squares ( a , b ) ; }
Tetrahedral Numbers | CPP Program to find the nth tetrahedral number ; Function to find Tetrahedral Number ; Driver Code
#include <iostream> NEW_LINE using namespace std ; int tetrahedralNumber ( int n ) { return ( n * ( n + 1 ) * ( n + 2 ) ) / 6 ; } int main ( ) { int n = 5 ; cout << tetrahedralNumber ( n ) << endl ; return 0 ; }
Euler 's Four Square Identity | CPP code to verify euler 's four square identity ; function to check euler four square identity ; loops checking the sum of squares ; sum of 2 squares ; sum of 3 squares ; sum of 4 squares ; product of 2 numbers represented as sum of four squares i , j , k , l ; product of 2 numbers a and b represented as sum of four squares i , j , k , l ; Driver code ; given numbers can be represented as sum of 4 squares By euler 's four square identity product also can be represented as sum of 4 squares
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define show ( x ) cout << #x << " = " << x << " NEW_LINE " void check_euler_four_square_identity ( int a , int b , int ab ) { int s = 0 ; for ( int i = 0 ; i * i <= ab ; i ++ ) { s = i * i ; for ( int j = i ; j * j <= ab ; j ++ ) { s = j * j + i * i ; for ( int k = j ; k * k <= ab ; k ++ ) { s = k * k + j * j + i * i ; for ( int l = k ; l * l <= ab ; l ++ ) { s = l * l + k * k + j * j + i * i ; if ( s == ab ) { show ( i ) ; show ( j ) ; show ( k ) ; show ( l ) ; cout << " " << " Product ▁ of ▁ " << a << " ▁ and ▁ " << b ; cout << " ▁ can ▁ be ▁ written " << " ▁ as ▁ sum ▁ of ▁ squares ▁ of ▁ i , ▁ " << " j , ▁ k , ▁ l STRNEWLINE " ; cout << ab << " ▁ = ▁ " ; cout << i << " * " << i << " ▁ + ▁ " ; cout << j << " * " << j << " ▁ + ▁ " ; cout << k << " * " << k << " ▁ + ▁ " ; cout << l << " * " << l << " STRNEWLINE " ; cout << " STRNEWLINE " ; } } } } } } int main ( ) { int ab = a * b ; check_euler_four_square_identity ( a , b , ab ) ; return 0 ; }
Number of solutions to Modular Equations | C ++ Program to find number of possible values of X to satisfy A mod X = B ; Returns the number of divisors of ( A - B ) greater than B ; if N is divisible by i ; count only the divisors greater than B ; checking if a divisor isnt counted twice ; Utility function to calculate number of all possible values of X for which the modular equation holds true ; if A = B there are infinitely many solutions to equation or we say X can take infinitely many values > A . We return - 1 in this case ; if A < B , there are no possible values of X satisfying the equation ; the last case is when A > B , here we calculate the number of divisors of ( A - B ) , which are greater than B ; Wrapper function for numberOfPossibleWaysUtil ( ) ; if infinitely many solutions available ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int calculateDivisors ( int A , int B ) { int N = ( A - B ) ; int noOfDivisors = 0 ; for ( int i = 1 ; i <= sqrt ( N ) ; i ++ ) { if ( ( N % i ) == 0 ) { if ( i > B ) noOfDivisors ++ ; if ( ( N / i ) != i && ( N / i ) > B ) noOfDivisors ++ ; } } return noOfDivisors ; } int numberOfPossibleWaysUtil ( int A , int B ) { if ( A == B ) return -1 ; if ( A < B ) return 0 ; int noOfDivisors = 0 ; noOfDivisors = calculateDivisors ( A , B ) ; return noOfDivisors ; } void numberOfPossibleWays ( int A , int B ) { int noOfSolutions = numberOfPossibleWaysUtil ( A , B ) ; if ( noOfSolutions == -1 ) { cout << " For ▁ A ▁ = ▁ " << A << " ▁ and ▁ B ▁ = ▁ " << B << " , ▁ X ▁ can ▁ take ▁ Infinitely ▁ many ▁ values " " ▁ greater ▁ than ▁ " << A << " STRNEWLINE " ; } else { cout << " For ▁ A ▁ = ▁ " << A << " ▁ and ▁ B ▁ = ▁ " << B << " , ▁ X ▁ can ▁ take ▁ " << noOfSolutions << " ▁ values STRNEWLINE " ; } } int main ( ) { int A = 26 , B = 2 ; numberOfPossibleWays ( A , B ) ; A = 21 , B = 5 ; numberOfPossibleWays ( A , B ) ; return 0 ; }
Perfect power ( 1 , 4 , 8 , 9 , 16 , 25 , 27 , ... ) | C ++ program to count number of numbers from 1 to n are of type x ^ y where x > 0 and y > 1 ; Function that keeps all the odd power numbers upto n ; We need exclude perfect squares . ; sort the vector ; Return sum of odd and even powers . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define ll long long NEW_LINE int powerNumbers ( int n ) { vector < int > v ; for ( ll i = 2 ; i * i * i <= n ; i ++ ) { ll j = i * i ; while ( j * i <= n ) { j *= i ; ll s = sqrt ( j ) ; if ( s * s != j ) v . push_back ( j ) ; } } sort ( v . begin ( ) , v . end ( ) ) ; v . erase ( unique ( v . begin ( ) , v . end ( ) ) , v . end ( ) ) ; return v . size ( ) + ( ll ) sqrt ( n ) ; } int main ( ) { cout << powerNumbers ( 50 ) ; return 0 ; }
Variance and standard | CPP program to find mean and variance of a matrix . ; variance function declaration ; Function for calculating mean ; Calculating sum ; Returning mean ; Function for calculating variance ; subtracting mean from elements ; a [ i ] [ j ] = fabs ( a [ i ] [ j ] ) ; squaring each terms ; taking sum ; driver program ; declaring and initializing matrix ; for mean ; for variance ; for standard deviation ; displaying variance and deviation
#include <bits/stdc++.h> NEW_LINE using namespace std ; int variance ( int , int , int ) ; int mean ( int a [ ] [ 3 ] , int n ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = 0 ; j < n ; j ++ ) sum += a [ i ] [ j ] ; return sum / ( n * n ) ; } int variance ( int a [ ] [ 3 ] , int n , int m ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { a [ i ] [ j ] -= m ; a [ i ] [ j ] *= a [ i ] [ j ] ; } } for ( int i = 0 ; i < n ; i ++ ) for ( int j = 0 ; j < n ; j ++ ) sum += a [ i ] [ j ] ; return sum / ( n * n ) ; } int main ( ) { int mat [ 3 ] [ 3 ] = { { 1 , 2 , 3 } , { 4 , 5 , 6 } , { 7 , 8 , 9 } } ; int m = mean ( mat , 3 ) ; int var = variance ( mat , 3 , m ) ; int dev = sqrt ( var ) ; cout << " Mean : ▁ " << m << " STRNEWLINE " << " Variance : ▁ " << var << " STRNEWLINE " << " Deviation : ▁ " << dev << " STRNEWLINE " ; return 0 ; }
Find N Arithmetic Means between A and B | C ++ program to find n arithmetic means between A and B ; Prints N arithmetic means between A and B . ; calculate common difference ( d ) ; for finding N the arithmetic mean between A and B ; Driver code to test above
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printAMeans ( int A , int B , int N ) { float d = ( float ) ( B - A ) / ( N + 1 ) ; for ( int i = 1 ; i <= N ; i ++ ) cout << ( A + i * d ) << " ▁ " ; } int main ( ) { int A = 20 , B = 32 , N = 5 ; printAMeans ( A , B , N ) ; return 0 ; }
Sum of the series 1.2 . 3 + 2.3 . 4 + ... + n ( n + 1 ) ( n + 2 ) | Efficient CPP program to find sum of the series 1.2 . 3 + 2.3 . 4 + 3.4 . 5 + ... ; function to calculate sum of series ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int sumofseries ( int n ) { return ( n * ( n + 1 ) * ( n + 2 ) * ( n + 3 ) / 4 ) ; } int main ( ) { cout << sumofseries ( 3 ) << endl ; return 0 ; }
Largest number in [ 2 , 3 , . . n ] which is co | ; Returns true if i is co - prime with numbers in set [ 2 , 3 , ... m ] ; Running the loop till square root of n to reduce the time complexity from n ; Find the minimum of square root of n and m to run the loop until the smaller one ; Check from 2 to min ( m , sqrt ( n ) ) ; Function to find the largest number less than n which is Co - prime with all numbers from 2 to m ; Iterating from n to m + 1 to find the number ; checking every number for the given conditions ; The first number which satisfy the conditions is the answer ; If there is no number which satisfy the conditions , then print number does not exist . ; Driver Program
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isValid ( long long int i , long long int m ) { long long int sq_i = sqrt ( i ) ; long long int sq = min ( m , sq_i ) ; for ( long long int j = 2 ; j <= sq ; j ++ ) if ( i % j == 0 ) return false ; return true ; } void findLargestNum ( long long int n , long long int m ) { for ( long long int i = n ; i > m ; i -- ) { if ( isValid ( i , m ) ) { cout << i << ' ' ; return ; } } cout << " Number ▁ Doesn ' t ▁ Exists STRNEWLINE " ; } int main ( ) { long long int n = 16 , m = 3 ; findLargestNum ( n , m ) ; return 0 ; }
Check whether a given matrix is orthogonal or not | C ++ code to check whether a matrix is orthogonal or not ; Function to check orthogonalilty ; Find transpose ; Find product of a [ ] [ ] and its transpose ; Since we are multiplying with transpose of itself . We use ; Check if product is identity matrix ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 100 NEW_LINE bool isOrthogonal ( int a [ ] [ MAX ] , int m , int n ) { if ( m != n ) return false ; int trans [ n ] [ n ] ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = 0 ; j < n ; j ++ ) trans [ i ] [ j ] = a [ j ] [ i ] ; int prod [ n ] [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { int sum = 0 ; for ( int k = 0 ; k < n ; k ++ ) { sum = sum + ( a [ i ] [ k ] * a [ j ] [ k ] ) ; } prod [ i ] [ j ] = sum ; } } for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { if ( i != j && prod [ i ] [ j ] != 0 ) return false ; if ( i == j && prod [ i ] [ j ] != 1 ) return false ; } } return true ; } int main ( ) { int a [ ] [ MAX ] = { { 1 , 0 , 0 } , { 0 , 1 , 0 } , { 0 , 0 , 1 } } ; if ( isOrthogonal ( a , 3 , 3 ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Check if given number is perfect square | CPP program to find if x is a perfect square . ; Find floating point value of square root of x . ; if product of square root is equal , then return T / F ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPerfectSquare ( long double x ) { if ( x >= 0 ) { long long sr = sqrt ( x ) ; return ( sr * sr == x ) ; } return false ; } int main ( ) { long long x = 2502 ; if ( isPerfectSquare ( x ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Program to print GP ( Geometric Progression ) | CPP program to print GP . ; function to print GP ; Driver code ; starting number ; Common ratio ; N th term to be find
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printGP ( int a , int r , int n ) { int curr_term ; for ( int i = 0 ; i < n ; i ++ ) { curr_term = a * pow ( r , i ) ; cout << curr_term << " ▁ " ; } } int main ( ) { int a = 2 ; int r = 3 ; int n = 5 ; printGP ( a , r , n ) ; return 0 ; }
HCF of array of fractions ( or rational numbers ) | CPP program to find HCF of array of rational numbers ( fractions ) . ; hcf of two number ; find hcf of numerator series ; return hcf of numerator ; find lcm of denominator series ; ans contains LCM of arr [ 0 ] [ 1 ] , . . arr [ i ] [ 1 ] ; return lcm of denominator ; Core Function ; found hcf of numerator ; found lcm of denominator ; return result ; Main function ; Initialize the every row with size 2 ( 1 for numerator and 2 for denominator ) ; function for calculate the result ; print the result
#include <iostream> NEW_LINE using namespace std ; int gcd ( int a , int b ) { if ( a % b == 0 ) return b ; else return ( gcd ( b , a % b ) ) ; } int findHcf ( int * * arr , int size ) { int ans = arr [ 0 ] [ 0 ] ; for ( int i = 1 ; i < size ; i ++ ) ans = gcd ( ans , arr [ i ] [ 0 ] ) ; return ( ans ) ; } int findLcm ( int * * arr , int size ) { int ans = arr [ 0 ] [ 1 ] ; for ( int i = 1 ; i < size ; i ++ ) ans = ( ( ( arr [ i ] [ 1 ] * ans ) ) / ( gcd ( arr [ i ] [ 1 ] , ans ) ) ) ; return ( ans ) ; } int * hcfOfFraction ( int * * arr , int size ) { int hcf_of_num = findHcf ( arr , size ) ; int lcm_of_deno = findLcm ( arr , size ) ; int * result = new int [ 2 ] ; result [ 0 ] = hcf_of_num ; result [ 1 ] = lcm_of_deno ; for ( int i = result [ 0 ] / 2 ; i > 1 ; i -- ) { if ( ( result [ 1 ] % i == 0 ) && ( result [ 0 ] % i == 0 ) ) { result [ 1 ] /= i ; result [ 0 ] /= i ; } } return ( result ) ; } int main ( ) { int size = 4 ; int * * arr = new int * [ size ] ; for ( int i = 0 ; i < size ; i ++ ) arr [ i ] = new int [ 2 ] ; arr [ 0 ] [ 0 ] = 9 ; arr [ 0 ] [ 1 ] = 10 ; arr [ 1 ] [ 0 ] = 12 ; arr [ 1 ] [ 1 ] = 25 ; arr [ 2 ] [ 0 ] = 18 ; arr [ 2 ] [ 1 ] = 35 ; arr [ 3 ] [ 0 ] = 21 ; arr [ 3 ] [ 1 ] = 40 ; int * result = hcfOfFraction ( arr , size ) ; cout << result [ 0 ] << " , ▁ " << result [ 1 ] << endl ; return 0 ; }
Space efficient iterative method to Fibonacci number | C ++ code to find nth fibonacci ; get second MSB ; consectutively set all the bits ; returns the second MSB ; Multiply function ; Function to calculate F [ ] [ ] raise to the power n ; Base case ; take 2D array to store number 's ; run loop till MSB > 0 ; To return fibonacci number ; Driver Code ; Given n
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getMSB ( int n ) { n |= n >> 1 ; n |= n >> 2 ; n |= n >> 4 ; n |= n >> 8 ; n |= n >> 16 ; return ( ( n + 1 ) >> 2 ) ; } void multiply ( int F [ 2 ] [ 2 ] , int M [ 2 ] [ 2 ] ) { int x = F [ 0 ] [ 0 ] * M [ 0 ] [ 0 ] + F [ 0 ] [ 1 ] * M [ 1 ] [ 0 ] ; int y = F [ 0 ] [ 0 ] * M [ 0 ] [ 1 ] + F [ 0 ] [ 1 ] * M [ 1 ] [ 1 ] ; int z = F [ 1 ] [ 0 ] * M [ 0 ] [ 0 ] + F [ 1 ] [ 1 ] * M [ 1 ] [ 0 ] ; int w = F [ 1 ] [ 0 ] * M [ 0 ] [ 1 ] + F [ 1 ] [ 1 ] * M [ 1 ] [ 1 ] ; F [ 0 ] [ 0 ] = x ; F [ 0 ] [ 1 ] = y ; F [ 1 ] [ 0 ] = z ; F [ 1 ] [ 1 ] = w ; } void power ( int F [ 2 ] [ 2 ] , int n ) { if ( n == 0 n == 1 ) return ; int M [ 2 ] [ 2 ] = { 1 , 1 , 1 , 0 } ; for ( int m = getMSB ( n ) ; m ; m = m >> 1 ) { multiply ( F , F ) ; if ( n & m ) { multiply ( F , M ) ; } } } int fib ( int n ) { int F [ 2 ] [ 2 ] = { { 1 , 1 } , { 1 , 0 } } ; if ( n == 0 ) return 0 ; power ( F , n - 1 ) ; return F [ 0 ] [ 0 ] ; } int main ( ) { int n = 6 ; cout << fib ( n ) << " ▁ " ; return 0 ; }
Stern | CPP program to print Brocot Sequence ; loop to create sequence ; adding sum of considered element and it 's precedent ; adding next considered element ; printing sequence . . ; Driver code ; adding first two element in the sequence
#include <bits/stdc++.h> NEW_LINE using namespace std ; void SternSequenceFunc ( vector < int > & BrocotSequence , int n ) { for ( int i = 1 ; BrocotSequence . size ( ) < n ; i ++ ) { int considered_element = BrocotSequence [ i ] ; int precedent = BrocotSequence [ i - 1 ] ; BrocotSequence . push_back ( considered_element + precedent ) ; BrocotSequence . push_back ( considered_element ) ; } for ( int i = 0 ; i < 15 ; ++ i ) cout << BrocotSequence [ i ] << " ▁ " ; } int main ( ) { int n = 15 ; vector < int > BrocotSequence ; BrocotSequence . push_back ( 1 ) ; BrocotSequence . push_back ( 1 ) ; SternSequenceFunc ( BrocotSequence , n ) ; return 0 ; }
Counting numbers whose difference from reverse is a product of k | C ++ program to Count the numbers within a given range in which when you subtract a number from its reverse , the difference is a product of k ; function to check if the number and its reverse have their absolute difference divisible by k ; reverse the number ; Driver code
#include <iostream> NEW_LINE using namespace std ; bool isRevDiffDivisible ( int x , int k ) { int n = x ; int m = 0 ; int flag ; while ( x > 0 ) { m = m * 10 + x % 10 ; x /= 10 ; } return ( abs ( n - m ) % k == 0 ) ; } int countNumbers ( int l , int r , int k ) { int count = 0 ; for ( int i = l ; i <= r ; i ++ ) if ( isRevDiffDivisible ( i , k ) ) ++ count ; return count ; } int main ( ) { int l = 20 , r = 23 , k = 6 ; cout << countNumbers ( l , r , k ) << endl ; return 0 ; }
Check for Amicable Pair | CPP program to check if two numbers are Amicable or not . ; Function to calculate sum of all proper divisors of a given number ; Sum of divisors ; find all divisors which divides ' num ' ; if ' i ' is divisor of ' n ' ; if both divisors are same then add it once else add both ; Add 1 and n to result as above loop considers proper divisors greater than 1. ; Returns true if x and y are Amicable else false . ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int divSum ( int n ) { int result = 0 ; for ( int i = 2 ; i <= sqrt ( n ) ; i ++ ) { if ( n % i == 0 ) { if ( i == ( n / i ) ) result += i ; else result += ( i + n / i ) ; } } return ( result + 1 ) ; } bool areAmicable ( int x , int y ) { if ( divSum ( x ) != y ) return false ; return ( divSum ( y ) == x ) ; } int main ( ) { int x = 220 , y = 284 ; if ( areAmicable ( x , y ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Program to print non square numbers | CPP program to print first n non - square numbers . ; Function to check perfect square ; function to print all non square number ; variable which stores the count ; not perfect square ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPerfectSquare ( int n ) { if ( n < 0 ) return false ; int root = round ( sqrt ( n ) ) ) ; return n == root * root ; } void printnonsquare ( int n ) { int count = 0 ; for ( int i = 1 ; count < n ; ++ i ) { if ( ! isPerfectSquare ( i ) ) { cout << i << " ▁ " ; count ++ ; } } } int main ( ) { int n = 10 ; printnonsquare ( n ) ; return 0 ; }
Program to print non square numbers | CPP program to print first n non square number ; Returns n - th non - square number . ; loop to print non squares below n ; Driver code
#include <bits/stdc++.h> NEW_LINE int nonsquare ( int n ) { return n + ( int ) ( 0.5 + sqrt ( n ) ) ; } void printNonSquare ( int n ) { for ( int i = 1 ; i <= n ; i ++ ) printf ( " % d ▁ " , nonsquare ( i ) ) ; } int main ( ) { int n = 10 ; printNonSquare ( n ) ; return 0 ; }
Ludic Numbers | C ++ code to print Lucid number smaller than or equal to n . ; Returns a list containing all Ludic numbers smaller than or equal to n . ; ludics list contain all the ludic numbers ; Here we have to start with index 1 and will remove nothing from the list ; Here first item should be included in the list and the deletion is referred by this first item in the loop . ; Remove_index variable is used to store the next index which we want to delete ; Removing the next item ; Remove_index is updated so that we get the next index for deletion ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > getLudic ( int n ) { vector < int > ludics ; for ( int i = 1 ; i <= n ; i ++ ) ludics . push_back ( i ) ; for ( int index = 1 ; index < ludics . size ( ) ; index ++ ) { int first_ludic = ludics [ index ] ; int remove_index = index + first_ludic ; while ( remove_index < ludics . size ( ) ) { auto it = ludics . begin ( ) ; it = it + remove_index ; ludics . erase ( it ) ; remove_index = remove_index + first_ludic - 1 ; } } return ludics ; } int main ( ) { int n = 25 ; vector < int > ans = getLudic ( n ) ; cout << " [ " ; for ( int i = 0 ; i < ans . size ( ) - 1 ; i ++ ) { cout << ans [ i ] << " , ▁ " ; } cout << ans [ ans . size ( ) - 1 ] << " ] " ; return 0 ; }
Prime Triplet | C ++ program to find prime triplets smaller than or equal to n . ; function to detect prime number here we have used sieve method https : www . geeksforgeeks . org / sieve - of - eratosthenes / to detect prime number ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; function to print prime triplets ; Finding all primes from 1 to n ; triplets of form ( p , p + 2 , p + 6 ) ; triplets of form ( p , p + 4 , p + 6 ) ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void sieve ( int n , bool prime [ ] ) { for ( int p = 2 ; p * p <= n ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * 2 ; i <= n ; i += p ) prime [ i ] = false ; } } } void printPrimeTriplets ( int n ) { bool prime [ n + 1 ] ; memset ( prime , true , sizeof ( prime ) ) ; sieve ( n , prime ) ; cout << " The ▁ prime ▁ triplets ▁ from ▁ 1 ▁ to ▁ " << n << " are ▁ : " << endl ; for ( int i = 2 ; i <= n - 6 ; ++ i ) { if ( prime [ i ] && prime [ i + 2 ] && prime [ i + 6 ] ) cout << i << " ▁ " << ( i + 2 ) << " ▁ " << ( i + 6 ) << endl ; else if ( prime [ i ] && prime [ i + 4 ] && prime [ i + 6 ] ) cout << i << " ▁ " << ( i + 4 ) << " ▁ " << ( i + 6 ) << endl ; } } int main ( ) { int n = 25 ; printPrimeTriplets ( n ) ; return 0 ; }
Program to compare two fractions | CPP program to find max between two Rational numbers ; Get max of the two fractions ; Declare nume1 and nume2 for get the value of first numerator and second numerator ; Compute ad - bc ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Fraction { int num , den ; } ; Fraction maxFraction ( Fraction first , Fraction sec ) { int a = first . num ; int b = first . den ; int c = sec . num ; int d = sec . den ; int Y = a * d - b * c ; return ( Y > 0 ) ? first : sec ; } int main ( ) { Fraction first = { 3 , 2 } ; Fraction sec = { 3 , 4 } ; Fraction res = maxFraction ( first , sec ) ; cout << res . num << " / " << res . den ; return 0 ; }
Find the nearest odd and even perfect squares of odd and even array elements respectively | C ++ program to implement the above approach ; Function to find the nearest even and odd perfect squares for even and odd array elements ; Traverse the array ; Calculate square root of current array element ; If both are of same parity ; Otherwise ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void nearestPerfectSquare ( int arr [ ] , int N ) { for ( int i = 0 ; i < N ; i ++ ) { int sr = sqrt ( arr [ i ] ) ; if ( ( sr & 1 ) == ( arr [ i ] & 1 ) ) cout << sr * sr << " ▁ " ; else { sr ++ ; cout << sr * sr << " ▁ " ; } } } int main ( ) { int arr [ ] = { 6 , 3 , 2 , 15 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; nearestPerfectSquare ( arr , N ) ; return 0 ; }