text
stringlengths
17
3.65k
code
stringlengths
60
5.26k
Largest ellipse that can be inscribed within a rectangle which in turn is inscribed within a semicircle | C # Program to find the biggest ellipse which can be inscribed within a rectangle which in turn is inscribed within a semicircle ; Function to find the area of the biggest ellipse ; the radius cannot be negative ; area of the ellipse ; Driver code
using System ; class GFG { static float ellipsearea ( float r ) { if ( r < 0 ) return - 1 ; float a = ( float ) ( ( 3.14 * r * r ) / 4 ) ; return a ; } public static void Main ( ) { float r = 5 ; Console . WriteLine ( ellipsearea ( r ) ) ; } }
Find the minimum number of operations required to make all array elements equal | C # implementation of the above approach ; Function to return the minimum operations required to make all array elements equal ; To store the frequency of all the array elements ; Traverse through array elements and update frequencies ; To store the maximum frequency of an element from the array ; Traverse through the map and find the maximum frequency for any element ; Return the minimum operations required ; Driver code
using System ; using System . Linq ; using System . Collections . Generic ; class GFG { static int minOperations ( int [ ] arr , int n ) { Dictionary < int , int > m = new Dictionary < int , int > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( m . ContainsKey ( arr [ i ] ) ) { var val = m [ arr [ i ] ] ; m . Remove ( arr [ i ] ) ; m . Add ( arr [ i ] , val + 1 ) ; } else { m . Add ( arr [ i ] , 1 ) ; } } int maxFreq = int . MinValue ; maxFreq = m . Values . Max ( ) ; return ( n - maxFreq ) ; } public static void Main ( String [ ] args ) { int [ ] arr = { 2 , 4 , 6 } ; int n = arr . Length ; Console . WriteLine ( minOperations ( arr , n ) ) ; } }
Count all prefixes of the given binary array which are divisible by x | C # implementation of the approach ; Function to return the count of total binary prefix which are divisible by x ; Initialize with zero ; Convert all prefixes to decimal ; If number is divisible by x then increase count ; Driver Code
using System ; class GfG { static int CntDivbyX ( int [ ] arr , int n , int x ) { int number = 0 ; int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { number = number * 2 + arr [ i ] ; if ( ( number % x == 0 ) ) count += 1 ; } return count ; } public static void Main ( ) { int [ ] arr = { 1 , 0 , 1 , 0 , 1 , 1 , 0 } ; int n = arr . Length ; int x = 2 ; Console . WriteLine ( CntDivbyX ( arr , n , x ) ) ; } }
Count consecutive pairs of same elements | C # implementation of the approach ; Function to return the count of consecutive elements in the array which are equal ; If consecutive elements are same ; Driver Code
using System ; class GfG { static int countCon ( int [ ] ar , int n ) { int cnt = 0 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( ar [ i ] == ar [ i + 1 ] ) cnt ++ ; } return cnt ; } public static void Main ( ) { int [ ] ar = { 1 , 2 , 2 , 3 , 4 , 4 , 5 , 5 , 5 , 5 } ; int n = ar . Length ; Console . WriteLine ( countCon ( ar , n ) ) ; } }
Reduce the fraction to its lowest form | C # program to reduce a fraction x / y to its lowest form ; Function to reduce a fraction to its lowest form ; Driver Code
using System ; class GFG { static void reduceFraction ( int x , int y ) { int d ; d = __gcd ( x , y ) ; x = x / d ; y = y / d ; Console . WriteLine ( " x ▁ = ▁ " + x + " , ▁ y ▁ = ▁ " + y ) ; } static int __gcd ( int a , int b ) { if ( b == 0 ) return a ; return __gcd ( b , a % b ) ; } public static void Main ( String [ ] args ) { int x = 16 ; int y = 10 ; reduceFraction ( x , y ) ; } }
Number of ways of choosing K equal substrings of any length for every query | C # code to print level order traversal in sorted order ; Function to generate all the sub - strings ; Length of the string ; Generate all sub - strings ; Count the occurrence of every sub - string ; Compute the Binomial Coefficient ; Calculate value of Binomial Coefficient in bottom up manner ; Base Cases ; Calculate value using previously stored values ; Function to return the result for a query ; Iterate for every unique sub - string ; Count the combinations ; Driver code ; Get all the sub - strings Store the occurrence of all the sub - strings ; Pre - computation ; Queries ; Perform queries
using System ; using System . Collections . Generic ; class GFG { static int maxlen = 100 ; public static void generateSubStrings ( String s , Dictionary < String , int > mpp ) { int l = s . Length ; for ( int i = 0 ; i < l ; i ++ ) { String temp = " " ; for ( int j = i ; j < l ; j ++ ) { temp += s [ j ] ; if ( mpp . ContainsKey ( temp ) ) { mpp [ temp ] = ++ mpp [ temp ] ; } else mpp . Add ( temp , 1 ) ; } } } public static void binomialCoeff ( int [ , ] C ) { int i , j ; for ( i = 1 ; i < 100 ; i ++ ) { for ( j = 0 ; j < 100 ; j ++ ) { if ( j == 0 j == i ) C [ i , j ] = 1 ; else C [ i , j ] = C [ i - 1 , j - 1 ] + C [ i - 1 , j ] ; } } } public static int answerQuery ( Dictionary < String , int > mpp , int [ , ] C , int k ) { int ans = 0 ; foreach ( KeyValuePair < String , int > entry in mpp ) { if ( entry . Value >= k ) ans += C [ entry . Value , k ] ; } return ans ; } public static void Main ( String [ ] args ) { String s = " aabaab " ; Dictionary < String , int > mpp = new Dictionary < String , int > ( ) ; generateSubStrings ( s , mpp ) ; int [ , ] C = new int [ maxlen , maxlen ] ; binomialCoeff ( C ) ; int [ ] queries = { 2 , 3 , 4 } ; int q = queries . Length ; for ( int i = 0 ; i < q ; i ++ ) Console . WriteLine ( answerQuery ( mpp , C , queries [ i ] ) ) ; } }
Times required by Simple interest for the Principal to become Y times itself | C # implementation for above approach ; Function to return the no . of years ; Driver code
using System ; class GFG { static float noOfYears ( int t1 , int n1 , int t2 ) { float years = ( ( t2 - 1 ) * n1 / ( float ) ( t1 - 1 ) ) ; return years ; } public static void Main ( String [ ] args ) { int T1 = 3 , N1 = 5 , T2 = 6 ; Console . WriteLine ( noOfYears ( T1 , N1 , T2 ) ) ; } }
Check if a given number divides the sum of the factorials of its digits | C # implementation of the approach ; Function that returns true if n divides the sum of the factorials of its digits ; To store factorials of digits ; To store sum of the factorials of the digits ; Store copy of the given number ; Store sum of the factorials of the digits ; If it is divisible ; Driver code
using System ; class GFG { static bool isPossible ( int n ) { int [ ] fac = new int [ 10 ] ; fac [ 0 ] = fac [ 1 ] = 1 ; for ( int i = 2 ; i < 10 ; i ++ ) fac [ i ] = fac [ i - 1 ] * i ; int sum = 0 ; int x = n ; while ( x != 0 ) { sum += fac [ x % 10 ] ; x /= 10 ; } if ( sum % n == 0 ) return true ; return false ; } public static void Main ( ) { int n = 19 ; if ( isPossible ( n ) ) Console . WriteLine ( " Yes " ) ; else Console . WriteLine ( " No " ) ; } }
Find the longest subsequence of an array having LCM at most K | C # implementation of the approach ; Function to find the longest subsequence having LCM less than or equal to K ; Map to store unique elements and their frequencies ; Update the frequencies ; Array to store the count of numbers whom 1 <= X <= K is a multiple of ; Check every unique element ; Find all its multiples <= K ; Store its frequency ; Obtain the number having maximum count ; Condition to check if answer doesn 't exist ; Print the answer ; Driver code
using System ; using System . Collections . Generic ; class GFG { static void findSubsequence ( int [ ] arr , int n , int k ) { Dictionary < int , int > M = new Dictionary < int , int > ( ) ; for ( int i = 0 ; i < n ; ++ i ) { if ( M . ContainsKey ( arr [ i ] ) ) M [ arr [ i ] ] ++ ; else M [ arr [ i ] ] = 1 ; } int [ ] numCount = new int [ k + 1 ] ; for ( int i = 0 ; i <= k ; ++ i ) numCount [ i ] = 0 ; Dictionary < int , int > . KeyCollection keyColl = M . Keys ; foreach ( int key in keyColl ) { if ( key <= k ) { for ( int i = 1 ; ; ++ i ) { if ( key * i > k ) break ; numCount [ key * i ] += M [ key ] ; } } else break ; } int lcm = 0 , length = 0 ; for ( int i = 1 ; i <= k ; ++ i ) { if ( numCount [ i ] > length ) { length = numCount [ i ] ; lcm = i ; } } if ( lcm == 0 ) Console . WriteLine ( - 1 ) ; else { Console . WriteLine ( " LCM ▁ = ▁ " + lcm + " ▁ Length ▁ = ▁ " + length ) ; Console . Write ( " Indexes ▁ = ▁ " ) ; for ( int i = 0 ; i < n ; ++ i ) if ( lcm % arr [ i ] == 0 ) Console . Write ( i + " ▁ " ) ; } } public static void Main ( ) { int k = 14 ; int [ ] arr = { 2 , 3 , 4 , 5 } ; int n = arr . Length ; findSubsequence ( arr , n , k ) ; } }
Count number of binary strings of length N having only 0 ' s ▁ and ▁ 1' s | C # implementation of the above approach ; Iterative Function to calculate ( x ^ y ) % p in O ( log y ) ; x = x % p ; Update x if it is more than or equal to p ; If y is odd , multiply x with result ; y must be even now y = y >> 1 ; y = y / 2 ; Function to count the number of binary strings of length N having only 0 ' s ▁ and ▁ 1' s ; Driver code
using System ; class GFG { static int mod = ( int ) ( 1e9 + 7 ) ; static int power ( int x , int y , int p ) { while ( y > 0 ) { if ( ( y & 1 ) == 1 ) res = ( res * x ) % p ; x = ( x * x ) % p ; } return res ; } static int findCount ( int N ) { int count = power ( 2 , N , mod ) ; return count ; } public static void Main ( ) { int N = 25 ; Console . WriteLine ( findCount ( N ) ) ; } }
XOR of all the elements in the given range [ L , R ] | C # implementation of the approach ; Function to return the most significant bit ; Function to return the required XOR ; Finding the MSB ; Value of the current bit to be added ; To store the final answer ; Loop for case 1 ; Edge case when both the integers lie in the same segment of continuous 1 s ; To store whether parity of count is odd ; Updating the answer if parity is odd ; Updating the number to be added ; Case 2 ; Driver code ; Final answer
using System ; class GFG { static int msb ( int x ) { int ret = 0 ; while ( ( x >> ( ret + 1 ) ) != 0 ) ret ++ ; return ret ; } static int xorRange ( int l , int r ) { int max_bit = msb ( r ) ; int mul = 2 ; int ans = 0 ; for ( int i = 1 ; i <= max_bit ; i ++ ) { if ( ( l / mul ) * mul == ( r / mul ) * mul ) { if ( ( ( l & ( 1 << i ) ) != 0 ) && ( r - l + 1 ) % 2 == 1 ) ans += mul ; mul *= 2 ; continue ; } int odd_c = 0 ; if ( ( ( l & ( 1 << i ) ) != 0 ) && l % 2 == 1 ) odd_c = ( odd_c ^ 1 ) ; if ( ( ( r & ( 1 << i ) ) != 0 ) && r % 2 == 0 ) odd_c = ( odd_c ^ 1 ) ; if ( odd_c != 0 ) ans += mul ; mul *= 2 ; } int zero_bit_cnt = zero_bit_cnt = ( r - l + 1 ) / 2 ; if ( l % 2 == 1 && r % 2 == 1 ) zero_bit_cnt ++ ; if ( zero_bit_cnt % 2 == 1 ) ans ++ ; return ans ; } public static void Main ( String [ ] args ) { int l = 1 , r = 4 ; Console . Write ( xorRange ( l , r ) ) ; } }
XOR of all the elements in the given range [ L , R ] | C # implementation of the approach ; Function to return the required XOR ; Modulus operator are expensive on most of the computers . n & 3 will be equivalent to n % 4 n % 4 ; If n is a multiple of 4 ; If n % 4 gives remainder 1 ; If n % 4 gives remainder 2 ; If n % 4 gives remainder 3 ; Driver code
using System ; class GFG { static long computeXOR ( int n ) { int x = n & 3 ; switch ( x ) { case 0 : return n ; case 1 : return 1 ; case 2 : return n + 1 ; case 3 : return 0 ; } return 0 ; } static void Main ( ) { int l = 1 , r = 4 ; Console . WriteLine ( computeXOR ( r ) ^ computeXOR ( l - 1 ) ) ; } }
Find the number of integers from 1 to n which contains digits 0 ' s ▁ and ▁ 1' s only | C # program to find the number of integers from 1 to n which contains digits 0 ' s ▁ and ▁ 1' s only ; Function to find the number of integers from 1 to n which contains 0 ' s ▁ and ▁ 1' s only ; If number is greater than n ; otherwise add count this number and call two functions ; Driver code
using System ; class GFG { static int countNumbers ( int x , int n ) { if ( x > n ) return 0 ; return 1 + countNumbers ( x * 10 , n ) + countNumbers ( x * 10 + 1 , n ) ; } public static void Main ( ) { int n = 120 ; Console . WriteLine ( countNumbers ( 1 , n ) ) ; } }
Check if factorial of N is divisible by the sum of squares of first N natural numbers | C # implementation of the approach ; Function to count number of times prime P divide factorial N ; Lengendre Formula ; Function to find count number of times all prime P divide summation ; Formula for summation of square after removing n and constant 6 ; Loop to traverse over all prime P which divide summation ; If Number itself is a Prime Number ; Driver Code
using System ; class GFG { static bool checkfact ( int N , int countprime , int prime ) { int countfact = 0 ; if ( prime == 2 prime == 3 ) countfact ++ ; int divide = prime ; while ( N / divide != 0 ) { countfact += N / divide ; divide = divide * divide ; } if ( countfact >= countprime ) return true ; else return false ; } static bool check ( int N ) { int sumsquares = ( N + 1 ) * ( 2 * N + 1 ) ; int countprime = 0 ; for ( int i = 2 ; i <= Math . Sqrt ( sumsquares ) ; i ++ ) { int flag = 0 ; while ( sumsquares % i == 0 ) { flag = 1 ; countprime ++ ; sumsquares /= i ; } if ( flag == 1 ) { if ( ! checkfact ( N - 1 , countprime , i ) ) return false ; countprime = 0 ; } } if ( sumsquares != 1 ) if ( ! checkfact ( N - 1 , 1 , sumsquares ) ) return false ; return true ; } public static void Main ( ) { int N = 5 ; if ( check ( N ) ) Console . WriteLine ( " Yes " ) ; else Console . WriteLine ( " No " ) ; } }
Count the number of non | C # program to count number of non increasing subarrays ; Initialize result ; Initialize length of current non increasing subarray ; Traverse through the array ; If arr [ i + 1 ] is less than or equal to arr [ i ] , then increment length ; Else Update count and reset length ; If last length is more than 1 ; Driver code
using System ; class GFG { static int countNonIncreasing ( int [ ] arr , int n ) { int cnt = 0 ; int len = 1 ; for ( int i = 0 ; i < n - 1 ; ++ i ) { if ( arr [ i + 1 ] <= arr [ i ] ) len ++ ; else { cnt += ( ( ( len + 1 ) * len ) / 2 ) ; len = 1 ; } } if ( len > 1 ) cnt += ( ( ( len + 1 ) * len ) / 2 ) ; return cnt ; } public static void Main ( String [ ] args ) { int [ ] arr = { 5 , 2 , 3 , 7 , 1 , 1 } ; int n = arr . Length ; Console . Write ( countNonIncreasing ( arr , n ) ) ; } }
Minimum array elements to be changed to make Recaman 's sequence | C # implementation of the approach ; First term of the sequence is always 0 ; Fill remaining terms using recursive formula ; If arr [ i - 1 ] - i is negative or already exists ; Function that returns minimum changes required ; Set to store first n Recaman numbers ; Generate and store first n Recaman numbers ; Insert first n Recaman numbers to set ; If current element of the array is present in the set ; Return the remaining number of elements in the set ; Driver code
using System ; using System . Collections . Generic ; class GFG { static int recamanGenerator ( int [ ] arr , int n ) { arr [ 0 ] = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { int temp = arr [ i - 1 ] - i ; int j ; for ( j = 0 ; j < i ; j ++ ) { if ( ( arr [ j ] == temp ) temp < 0 ) { temp = arr [ i - 1 ] + i ; break ; } } arr [ i ] = temp ; } return 0 ; } static int recamanArray ( int [ ] arr , int n ) { HashSet < int > s = new HashSet < int > ( ) ; int [ ] recaman = new int [ n + 1 ] ; recamanGenerator ( recaman , n ) ; for ( int i = 0 ; i < n ; i ++ ) s . Add ( recaman [ i ] ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( s . Contains ( arr [ i ] ) ) s . Remove ( arr [ i ] ) ; } return s . Count ; } static void Main ( ) { int [ ] arr = { 7 , 11 , 20 , 4 , 2 , 1 , 8 , 6 } ; int n = arr . Length ; Console . Write ( recamanArray ( arr , n ) ) ; } }
Check if product of array containing prime numbers is a perfect square | C # implementation of the approach ; Function that returns true if the product of all the array elements is a perfect square ; Update the frequencies of all the array elements ; If frequency of some element in the array is odd ; Driver code
using System ; using System . Collections . Generic ; class GFG { static bool isPerfectSquare ( int [ ] arr , int n ) { Dictionary < int , int > umap = new Dictionary < int , int > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( umap . ContainsKey ( arr [ i ] ) ) umap [ arr [ i ] ] ++ ; else umap [ arr [ i ] ] = 1 ; } Dictionary < int , int > . ValueCollection valueColl = umap . Values ; foreach ( int val in valueColl ) { if ( val % 2 == 1 ) return false ; } return true ; } public static void Main ( ) { int [ ] arr = { 2 , 2 , 7 , 7 } ; int n = arr . Length ; if ( isPerfectSquare ( arr , n ) ) Console . WriteLine ( " Yes " ) ; else Console . WriteLine ( " No " ) ; } }
Find the good permutation of first N natural numbers | C # implementation of the approach ; Function to print the good permutation of first N natural numbers ; If n is odd ; Otherwise ; Driver code
using System ; class GFG { static int printPermutation ( int n ) { if ( n % 2 != 0 ) { Console . WriteLine ( " - 1" ) ; } else for ( int i = 1 ; i <= n / 2 ; i ++ ) { Console . WriteLine ( 2 * i + " ▁ " + ( ( 2 * i ) - 1 ) + " ▁ " ) ; } return n ; } public static void Main ( String [ ] args ) { int n = 4 ; printPermutation ( n ) ; } }
Minimum number operations required to convert n to m | Set | C # implementation of the above approach ; Function to find the minimum number of steps ; If n exceeds M ; If N reaches the target ; The minimum of both the states will be the answer ; Driver code
using System ; class GFG { static int MAXN = 10000000 ; static int minimumSteps ( int n , int m , int a , int b ) { if ( n > m ) return MAXN ; if ( n == m ) return 0 ; return Math . Min ( 1 + minimumSteps ( n * a , m , a , b ) , 1 + minimumSteps ( n * b , m , a , b ) ) ; } public static void Main ( ) { int n = 120 , m = 51840 ; int a = 2 , b = 3 ; Console . WriteLine ( minimumSteps ( n , m , a , b ) ) ; } }
Minimum number of given operation required to convert n to m | C # implementation of the approach ; Function to return the minimum operations required ; Counting all 2 s ; Counting all 3 s ; If q contained only 2 and 3 as the only prime factors then it must be 1 now ; Driver code
using System ; class GFG { static int minOperations ( int n , int m ) { if ( m % n != 0 ) return - 1 ; int minOperations = 0 ; int q = m / n ; while ( q % 2 == 0 ) { q = q / 2 ; minOperations ++ ; } while ( q % 3 == 0 ) { q = q / 3 ; minOperations ++ ; } if ( q == 1 ) return minOperations ; return - 1 ; } public static void Main ( ) { int n = 120 , m = 51840 ; Console . WriteLine ( minOperations ( n , m ) ) ; } }
Sum of Fibonacci Numbers in a range | C # implementation of above approach ; Function to return the nth Fibonacci number ; Function to return the required sum ; To store the sum ; Calculate the sum ; Driver code
using System ; class GFG { static int fib ( int n ) { double phi = ( 1 + Math . Sqrt ( 5 ) ) / 2 ; return ( int ) Math . Round ( Math . Pow ( phi , n ) / Math . Sqrt ( 5 ) ) ; } static int calculateSum ( int l , int r ) { int sum = 0 ; for ( int i = l ; i <= r ; i ++ ) sum += fib ( i ) ; return sum ; } public static void Main ( ) { int l = 4 , r = 8 ; Console . WriteLine ( calculateSum ( l , r ) ) ; } }
Largest sphere that can be inscribed within a cube which is in turn inscribed within a right circular cone | C # Program to find the biggest sphere which is inscribed within a cube which in turn inscribed within a right circular cone ; Function to find the radius of the sphere ; height and radius cannot be negative ; radius of the sphere ; Driver code
using System ; class GFG { static float sphereSide ( float h , float r ) { if ( h < 0 && r < 0 ) return - 1 ; float R = ( float ) ( ( h * r * Math . Sqrt ( 2 ) ) / ( h + Math . Sqrt ( 2 ) * r ) ) / 2 ; return R ; } public static void Main ( ) { float h = 5 , r = 6 ; Console . WriteLine ( sphereSide ( h , r ) ) ; } }
Find the number of ways to divide number into four parts such that a = c and b = d | C # implementation for above approach ; Function to find the number of ways to divide N into four parts such that a = c and b = d ; Driver code
class GFG { static int possibleways ( int n ) { if ( n % 2 == 1 ) return 0 ; else if ( n % 4 == 0 ) return n / 4 - 1 ; else return n / 4 ; } static void Main ( ) { int n = 20 ; System . Console . WriteLine ( possibleways ( n ) ) ; } }
Count sub | C # implementation of the approach ; Function to count sub - arrays whose product is divisible by K ; Calculate the product of the current sub - array ; If product of the current sub - array is divisible by K ; Driver code
using System ; class GFG { static int countSubarrays ( int [ ] arr , int n , int K ) { int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i ; j < n ; j ++ ) { long product = 1 ; for ( int x = i ; x <= j ; x ++ ) product *= arr [ x ] ; if ( product % K == 0 ) count ++ ; } } return count ; } public static void Main ( ) { int [ ] arr = { 6 , 2 , 8 } ; int n = arr . Length ; int K = 4 ; Console . WriteLine ( countSubarrays ( arr , n , K ) ) ; } }
Count sub | C # implementation for above approach ; Segment tree implemented as an array ; Function to build the segment tree ; Function to query product of sub - array [ l . . r ] in O ( log n ) time ; Function to count sub - arrays whose product is divisible by K ; Query segment tree to find product % k of the sub - array [ i . . j ] ; Driver code ; Build the segment tree
using System ; class GFG { static int MAX = 100002 ; static long [ ] tree = new long [ 4 * MAX ] ; static void build ( int node , int start , int end , int [ ] arr , int k ) { if ( start == end ) { tree [ node ] = ( 1L * arr [ start ] ) % k ; return ; } int mid = ( start + end ) >> 1 ; build ( 2 * node , start , mid , arr , k ) ; build ( 2 * node + 1 , mid + 1 , end , arr , k ) ; tree [ node ] = ( tree [ 2 * node ] * tree [ 2 * node + 1 ] ) % k ; } static long query ( int node , int start , int end , int l , int r , int k ) { if ( start > end start > r end < l ) { return 1 ; } if ( start >= l && end <= r ) { return tree [ node ] % k ; } int mid = ( start + end ) >> 1 ; long q1 = query ( 2 * node , start , mid , l , r , k ) ; long q2 = query ( 2 * node + 1 , mid + 1 , end , l , r , k ) ; return ( q1 * q2 ) % k ; } static long countSubarrays ( int [ ] arr , int n , int k ) { long count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i ; j < n ; j ++ ) { long product_mod_k = query ( 1 , 0 , n - 1 , i , j , k ) ; if ( product_mod_k == 0 ) { count ++ ; } } } return count ; } public static void Main ( String [ ] args ) { int [ ] arr = { 6 , 2 , 8 } ; int n = arr . Length ; int k = 4 ; build ( 1 , 0 , n - 1 , arr , k ) ; Console . WriteLine ( countSubarrays ( arr , n , k ) ) ; } }
Find a pair from the given array with maximum nCr value | C # implementation of the approach ; Function to print the pair that gives maximum nCr ; This gives the value of N in nCr ; Case 1 : When N is odd ; Case 2 : When N is even ; Driver code
using System ; using System . Collections . Generic ; class GFG { static void printMaxValPair ( List < long > v , int n ) { v . Sort ( ) ; long N = v [ ( int ) n - 1 ] ; if ( N % 2 == 1 ) { long first_maxima = N / 2 ; long second_maxima = first_maxima + 1 ; long ans1 = ( long ) 3e18 , ans2 = ( long ) 3e18 ; long from_left = - 1 , from_right = - 1 ; long from = - 1 ; for ( long i = 0 ; i < n ; ++ i ) { if ( v [ ( int ) i ] > first_maxima ) { from = i ; break ; } else { long diff = first_maxima - v [ ( int ) i ] ; if ( diff < ans1 ) { ans1 = diff ; from_left = v [ ( int ) i ] ; } } } from_right = v [ ( int ) from ] ; long diff1 = first_maxima - from_left ; long diff2 = from_right - second_maxima ; if ( diff1 < diff2 ) Console . WriteLine ( N + " ▁ " + from_left ) ; else Console . WriteLine ( N + " ▁ " + from_right ) ; } else { long maxima = N / 2 ; long ans1 = ( long ) 3e18 ; long R = - 1 ; for ( long i = 0 ; i < n - 1 ; ++ i ) { long diff = Math . Abs ( v [ ( int ) i ] - maxima ) ; if ( diff < ans1 ) { ans1 = diff ; R = v [ ( int ) i ] ; } } Console . WriteLine ( N + " ▁ " + R ) ; } } public static void Main ( String [ ] args ) { long [ ] arr = { 1 , 1 , 2 , 3 , 6 , 1 } ; List < long > v = new List < long > ( ) ; for ( int i = 0 ; i < arr . Length ; i ++ ) v . Add ( arr [ i ] ) ; int n = v . Count ; printMaxValPair ( v , n ) ; } }
Find the number of good permutations | C # implementation of the above approach . ; Function to return the count of good permutations ; For m = 0 , ans is 1 ; If k is greater than 1 ; If k is greater than 2 ; If k is greater than 3 ; Driver code
using System ; class GFG { static int Permutations ( int n , int k ) { int ans = 1 ; if ( k >= 2 ) ans += ( n ) * ( n - 1 ) / 2 ; if ( k >= 3 ) ans += ( n ) * ( n - 1 ) * ( n - 2 ) * 2 / 6 ; if ( k >= 4 ) ans += ( n ) * ( n - 1 ) * ( n - 2 ) * ( n - 3 ) * 9 / 24 ; return ans ; } public static void Main ( ) { int n = 5 , k = 2 ; Console . WriteLine ( Permutations ( n , k ) ) ; } }
Count integers in a range which are divisible by their euler totient value | C # implementation of the above approach . ; Function to return a ^ n ; Function to return count of integers that satisfy n % phi ( n ) = 0 ; Driver Code
using System ; class GFG { static long power ( long a , long n ) { if ( n == 0 ) return 1 ; long p = power ( a , n / 2 ) ; p = p * p ; if ( n % 2 == 1 ) p = p * a ; return p ; } static int countIntegers ( long l , long r ) { long ans = 0 , i = 1 ; long v = power ( 2 , i ) ; while ( v <= r ) { while ( v <= r ) { if ( v >= l ) ans ++ ; v = v * 3 ; } i ++ ; v = power ( 2 , i ) ; } if ( l == 1 ) ans ++ ; return ( int ) ans ; } public static void Main ( ) { long l = 12 , r = 21 ; Console . WriteLine ( countIntegers ( l , r ) ) ; } }
Number of pairs from the first N natural numbers whose sum is divisible by K | C # implementation of the approach ; Function to find the number of pairs from the set of natural numbers up to N whose sum is divisible by K ; Declaring a Hash to store count ; Storing the count of integers with a specific remainder in Hash array ; Check if K is even ; Count of pairs when both integers are divisible by K ; Count of pairs when one remainder is R and other remainder is K - R ; Count of pairs when both the remainders are K / 2 ; Count of pairs when both integers are divisible by K ; Count of pairs when one remainder is R and other remainder is K - R ; Driver code ; Print the count of pairs
class GfG { static int findPairCount ( int N , int K ) { int count = 0 ; int [ ] rem = new int [ K ] ; rem [ 0 ] = N / K ; for ( int i = 1 ; i < K ; i ++ ) rem [ i ] = ( N - i ) / K + 1 ; if ( K % 2 == 0 ) { count += ( rem [ 0 ] * ( rem [ 0 ] - 1 ) ) / 2 ; for ( int i = 1 ; i < K / 2 ; i ++ ) count += rem [ i ] * rem [ K - i ] ; count += ( rem [ K / 2 ] * ( rem [ K / 2 ] - 1 ) ) / 2 ; } else { count += ( rem [ 0 ] * ( rem [ 0 ] - 1 ) ) / 2 ; for ( int i = 1 ; i <= K / 2 ; i ++ ) count += rem [ i ] * rem [ K - i ] ; } return count ; } static void Main ( ) { int N = 10 , K = 4 ; System . Console . WriteLine ( findPairCount ( N , K ) ) ; } }
Find the sum of all Truncatable primes below N | C # implementation of the above approach . ; To check if a number is prime or not ; Sieve of Eratosthenes function to find all prime numbers ; Function to return the sum of all truncatable primes below n ; To store the required sum ; Check every number below n ; Check from right to left ; If number is not prime at any stage ; Check from left to right ; If number is not prime at any stage ; If flag is still true ; Return the required sum ; Driver code
using System ; using System . Collections . Generic ; class GFG { static int N = 1000005 ; static Boolean [ ] prime = new Boolean [ N ] ; static void sieve ( ) { Array . Fill ( prime , true ) ; prime [ 1 ] = false ; prime [ 0 ] = false ; for ( int i = 2 ; i < N ; i ++ ) { if ( prime [ i ] ) { for ( int j = i * 2 ; j < N ; j += i ) { prime [ j ] = false ; } } } } static int sumTruncatablePrimes ( int n ) { int sum = 0 ; for ( int i = 2 ; i < n ; i ++ ) { int num = i ; Boolean flag = true ; while ( num > 0 ) { if ( ! prime [ num ] ) { flag = false ; break ; } num /= 10 ; } num = i ; int power = 10 ; while ( num / power > 0 ) { if ( ! prime [ num % power ] ) { flag = false ; break ; } power *= 10 ; } if ( flag ) { sum += i ; } } return sum ; } public static void Main ( String [ ] args ) { int n = 25 ; sieve ( ) ; Console . WriteLine ( sumTruncatablePrimes ( n ) ) ; } }
Smallest and Largest N | C # implementation of the approach ; Function to print the largest and the smallest n - digit perfect squares ; Smallest n - digit perfect square ; Largest n - digit perfect square ; Driver code
using System ; public class GFG { static void nDigitPerfectSquares ( int n ) { int smallest = ( int ) Math . Pow ( Math . Ceiling ( Math . Sqrt ( Math . Pow ( 10 , n - 1 ) ) ) , 2 ) ; Console . Write ( smallest + " ▁ " ) ; int largest = ( int ) Math . Pow ( Math . Ceiling ( Math . Sqrt ( Math . Pow ( 10 , n ) ) ) - 1 , 2 ) ; Console . Write ( largest ) ; } public static void Main ( String [ ] args ) { int n = 4 ; nDigitPerfectSquares ( n ) ; } }
Maximum trace possible for any sub | C # program for the above approach ; Function to return the maximum trace possible for a sub - matrix of the given matrix ; Calculate the trace for each of the sub - matrix with top left corner at cell ( r , s ) ; Update the maximum trace ; Return the maximum trace ; Driver code
using System ; class GFG { static int N = 3 ; static int MaxTraceSub ( int [ ] [ ] mat ) { int max_trace = 0 ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) { int r = i , s = j , trace = 0 ; while ( r < N && s < N ) { trace += mat [ r ] [ s ] ; r ++ ; s ++ ; max_trace = Math . Max ( trace , max_trace ) ; } } } return max_trace ; } public static void Main ( ) { int [ ] [ ] mat = new int [ ] [ ] { new int [ ] { 10 , 2 , 5 } , new int [ ] { 6 , 10 , 4 } , new int [ ] { 2 , 7 , - 10 } } ; Console . WriteLine ( MaxTraceSub ( mat ) ) ; } }
Check if matrix can be converted to another matrix by transposing square sub | C # implementation of the approach ; Function that returns true if matrix1 can be converted to matrix2 with the given operation ; Traverse all the diagonals starting at first column ; Traverse in diagonal ; Store the diagonal elements ; Move up ; Sort the elements ; Check if they are same ; Traverse all the diagonals starting at last row ; Traverse in the diagonal ; Store diagonal elements ; Sort all elements ; Check for same ; If every element matches ; Driver code
using System ; using System . Collections . Generic ; class GFG { static readonly int n = 3 ; static readonly int m = 3 ; static bool check ( int [ , ] a , int [ , ] b ) { for ( int i = 0 ; i < n ; i ++ ) { List < int > v1 = new List < int > ( ) ; List < int > v2 = new List < int > ( ) ; int r = i ; int col = 0 ; while ( r >= 0 && col < m ) { v1 . Add ( a [ r , col ] ) ; v2 . Add ( b [ r , col ] ) ; r -- ; col ++ ; } v1 . Sort ( ) ; v2 . Sort ( ) ; for ( int j = 0 ; j < v1 . Count ; j ++ ) { if ( v1 [ j ] != v2 [ j ] ) { return false ; } } } for ( int j = 1 ; j < m ; j ++ ) { List < int > v1 = new List < int > ( ) ; List < int > v2 = new List < int > ( ) ; int r = n - 1 ; int col = j ; while ( r >= 0 && col < m ) { v1 . Add ( a [ r , col ] ) ; v2 . Add ( b [ r , col ] ) ; r -- ; col ++ ; } v1 . Sort ( ) ; v2 . Sort ( ) ; for ( int i = 0 ; i < v1 . Count ; i ++ ) { if ( v1 [ i ] != v2 [ i ] ) { return false ; } } } return true ; } public static void Main ( ) { int [ , ] a = { { 1 , 2 , 3 } , { 4 , 5 , 6 } , { 7 , 8 , 9 } } ; int [ , ] b = { { 1 , 4 , 7 } , { 2 , 5 , 6 } , { 3 , 8 , 9 } } ; if ( check ( a , b ) ) { Console . WriteLine ( " Yes " ) ; } else { Console . WriteLine ( " No " ) ; } } }
Last digit of Product of two Large or Small numbers ( a * b ) | CSharp implementation of the above approach ; Function to print last digit of product a * b ; Driver code
using System ; class Solution { public static void lastDigit ( String a , String b ) { int lastDig = ( a [ a . Length - 1 ] - '0' ) * ( b [ b . Length - 1 ] - '0' ) ; Console . Write ( lastDig % 10 ) ; } public static void Main ( ) { String a = "1234567891233" , b = "1234567891233156" ; lastDigit ( a , b ) ; } }
Smallest and Largest Palindrome with N Digits | C # implementation of the approach ; Function to print the smallest and largest palindrome with N digits ; Driver Code
using System ; class GfG { static void printPalindrome ( int n ) { if ( n == 1 ) { Console . WriteLine ( " Smallest ▁ Palindrome : ▁ 0" ) ; Console . WriteLine ( " Largest ▁ Palindrome : ▁ 9" ) ; } else { Console . WriteLine ( " Smallest ▁ Palindrome : ▁ " + ( int ) ( Math . Pow ( 10 , n - 1 ) ) + 1 ) ; Console . WriteLine ( " Largest ▁ Palindrome : ▁ " + ( ( int ) ( Math . Pow ( 10 , n ) ) - 1 ) ) ; } } public static void Main ( String [ ] args ) { int n = 4 ; printPalindrome ( n ) ; } }
Addition of two numbers without propagating Carry | C # implementation of the above approach ; Function to print sum of 2 numbers without propagating carry ; Reverse a ; Reverse b ; Generate sum Since length of both a and b are same , take any one of them . ; Extract digits from a and b and add ; If sum is single digit ; If sum is not single digit reverse sum ; Extract digits from sum and append to result ; Driver code
using System ; class GFG { static int printSum ( int a , int b ) { int res = 0 ; int temp1 = 0 , temp2 = 0 ; while ( a != 0 ) { temp1 = temp1 * 10 + ( a % 10 ) ; a /= 10 ; } a = temp1 ; while ( b != 0 ) { temp2 = temp2 * 10 + ( b % 10 ) ; b /= 10 ; } b = temp2 ; while ( a != 0 ) { int sum = ( a % 10 + b % 10 ) ; if ( sum / 10 == 0 ) res = res * 10 + sum ; else { temp1 = 0 ; while ( sum != 0 ) { temp1 = temp1 * 10 + ( sum % 10 ) ; sum /= 10 ; } sum = temp1 ; while ( sum != 0 ) { res = res * 10 + ( sum % 10 ) ; sum /= 10 ; } } a /= 10 ; b /= 10 ; } return res ; } public static void Main ( ) { int a = 7752 , b = 8834 ; Console . Write ( printSum ( a , b ) ) ; } }
Number of digits before the decimal point in the division of two numbers | C # implementation of the approach ; Function to return the number of digits before the decimal in a / b ; Absolute value of a / b ; If result is 0 ; Count number of digits in the result ; Return the required count of digits ; Driver code
using System ; class GFG { static int countDigits ( int a , int b ) { int count = 0 ; int p = Math . Abs ( a / b ) ; if ( p == 0 ) return 1 ; while ( p > 0 ) { count ++ ; p = p / 10 ; } return count ; } public static void Main ( ) { int a = 100 ; int b = 10 ; Console . Write ( countDigits ( a , b ) ) ; } }
Number of digits before the decimal point in the division of two numbers | C # implementation of the approach ; Function to return the number of digits before the decimal in a / b ; Return the required count of digits ; Driver code
using System ; class GFG { public static int countDigits ( int a , int b ) { double digits = Math . Log10 ( Math . Abs ( a ) ) - Math . Log10 ( Math . Abs ( b ) ) + 1 ; return ( int ) Math . Floor ( digits ) ; } static void Main ( ) { int a = 100 ; int b = 10 ; Console . Write ( countDigits ( a , b ) ) ; } }
Smallest odd number with N digits | C # implementation of the approach ; Function to return smallest odd with n digits ; Driver code
using System ; class Solution { static int smallestOdd ( int n ) { if ( n == 1 ) return 0 ; return Math . pow ( 10 , n - 1 ) + 1 ; } public static void Main ( ) { int n = 4 ; Console . Write ( smallestOdd ( n ) ) ; } }
Largest Even and Odd N | C # implementation of the approach ; Function to print the largest n - digit even and odd numbers ; Driver code
using System ; class GFG { static void findNumbers ( int n ) { int odd = ( int ) Math . Pow ( 10 , n ) - 1 ; int even = odd - 1 ; Console . WriteLine ( " Even ▁ = ▁ " + even ) ; Console . Write ( " Odd ▁ = ▁ " + odd ) ; } public static void Main ( ) { int n = 4 ; findNumbers ( n ) ; } }
Longest sub | C # implementation of the approach ; Function to return the length of the longest sub - array whose product of elements is 0 ; Driver code
using System ; class GFG { static int longestSubArray ( int [ ] arr , int n ) { bool isZeroPresent = false ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] == 0 ) { isZeroPresent = true ; break ; } } if ( isZeroPresent ) return n ; return 0 ; } public static void Main ( ) { int [ ] arr = { 1 , 2 , 3 , 0 , 1 , 2 , 0 } ; int n = arr . Length ; Console . Write ( longestSubArray ( arr , n ) ) ; } }
Smallest Even number with N digits | C # implementation of the approach ; Function to return smallest even number with n digits ; Driver code
using System ; class Solution { static int smallestEven ( int n ) { if ( n == 1 ) return 0 ; return Math . pow ( 10 , n - 1 ) ; } public static void Main ( ) { int n = 4 ; Console . Write ( smallestEven ( n ) ) ; } }
Maximize profit when divisibility by two numbers have associated profits | C # implementation of the approach ; Function to return the maximum profit ; min ( x , y ) * n / lcm ( a , b ) ; Driver code
using System ; class GFG { static int __gcd ( int a , int b ) { if ( b == 0 ) return a ; return __gcd ( b , a % b ) ; } static int maxProfit ( int n , int a , int b , int x , int y ) { int res = x * ( n / a ) ; res += y * ( n / b ) ; res -= Math . Min ( x , y ) * ( n / ( ( a * b ) / __gcd ( a , b ) ) ) ; return res ; } static void Main ( ) { int n = 6 , a = 6 , b = 2 , x = 8 , y = 2 ; Console . WriteLine ( maxProfit ( n , a , b , x , y ) ) ; } }
Series summation if T ( n ) is given and n is very large | C # implementation of the approach ; Function to return the sum of the given series ; Driver code
using System ; class GFG { const int MOD = 1000000007 ; static int sumOfSeries ( int n ) { int ans = ( int ) Math . Pow ( n % MOD , 2 ) ; return ( ans % MOD ) ; } public static void Main ( ) { int n = 10 ; Console . Write ( sumOfSeries ( n ) ) ; } }
Kth odd number in an array | C # implementation of the approach ; Function to return the kth odd element from the array ; Traverse the array ; If current element is odd ; If kth odd element is found ; Total odd elements in the array are < k ; Driver code
using System ; class GFG { static int kthOdd ( int [ ] arr , int n , int k ) { for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] % 2 == 1 ) k -- ; if ( k == 0 ) return arr [ i ] ; } return - 1 ; } public static void Main ( ) { int [ ] arr = { 1 , 2 , 3 , 4 , 5 } ; int n = arr . Length ; int k = 2 ; Console . WriteLine ( kthOdd ( arr , n , k ) ) ; } }
Find last five digits of a given five digit number raised to power five | C # program to find last five digits of a five digit number raised to power five ; Function to find the last five digits of a five digit number raised to power five ; Driver code
using System ; class GFG { public static void lastFiveDigits ( int n ) { n = ( n / 10000 ) * 10000 + ( ( n / 100 ) % 10 ) * 1000 + ( n % 10 ) * 100 + ( ( n / 10 ) % 10 ) * 10 + ( n / 1000 ) % 10 ; int ans = 1 ; for ( int i = 0 ; i < 5 ; i ++ ) { ans *= n ; ans %= 100000 ; } Console . WriteLine ( ans ) ; } public static void Main ( string [ ] args ) { int n = 12345 ; lastFiveDigits ( n ) ; } }
Sum of ( maximum element | C # implementation of the above approach ; Function to return a ^ n % mod ; Compute sum of max ( A ) - min ( A ) for all subsets ; Sort the array . ; Maxs = 2 ^ i - 1 ; Mins = 2 ^ ( n - 1 - i ) - 1 ; Driver code
using System ; using System . Collections ; class GFG { static int mod = 1000000007 ; static long power ( long a , long n ) { if ( n == 0 ) { return 1 ; } long p = power ( a , n / 2 ) % mod ; p = ( p * p ) % mod ; if ( n == 1 ) { p = ( p * a ) % mod ; } return p ; } static long computeSum ( int [ ] arr , int n ) { Array . Sort ( arr ) ; long sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { long maxs = ( power ( 2 , i ) - 1 + mod ) % mod ; maxs = ( maxs * arr [ i ] ) % mod ; long mins = ( power ( 2 , n - 1 - i ) - 1 + mod ) % mod ; mins = ( mins * arr [ i ] ) % mod ; long V = ( maxs - mins + mod ) % mod ; sum = ( sum + V ) % mod ; } return sum ; } public static void Main ( ) { int [ ] arr = { 4 , 3 , 1 } ; int n = arr . Length ; Console . WriteLine ( computeSum ( arr , n ) ) ; } }
Count of all N digit numbers such that num + Rev ( num ) = 10 ^ N | C # implementation of the approach ; Function to return the count of such numbers ; If n is odd ; Driver code
using System ; class GFG { static int countNumbers ( int n ) { if ( n % 2 == 1 ) return 0 ; return ( 9 * ( int ) Math . Pow ( 10 , n / 2 - 1 ) ) ; } public static void Main ( ) { int n = 2 ; Console . WriteLine ( countNumbers ( n ) ) ; } }
Count of numbers having only 1 set bit in the range [ 0 , n ] | C # implementation of the approach ; Function to return the required count ; To store the count of numbers ; Every power of 2 contains only 1 set bit ; Driver code
using System ; class GFG { static int count ( int n ) { int cnt = 0 ; int p = 1 ; while ( p <= n ) { cnt ++ ; p *= 2 ; } return cnt ; } public static void Main ( ) { int n = 7 ; Console . Write ( count ( n ) ) ; } }
Find the K | C # programme to find the K 'th minimum element from an array concatenated M times ; Function to find the K - th minimum element from an array concatenated M times ; Sort the elements in ascending order ; Return the K 'th Min element present at ( (K-1) / M ) index ; Driver Code
using System ; class GFG { static int KthMinValAfterMconcatenate ( int [ ] A , int N , int M , int K ) { Array . Sort ( A ) ; return ( A [ ( ( K - 1 ) / M ) ] ) ; } static void Main ( ) { int [ ] A = { 3 , 1 , 2 } ; int M = 3 , K = 4 ; int N = A . Length ; Console . WriteLine ( KthMinValAfterMconcatenate ( A , N , M , K ) ) ; } }
Sum of all i such that ( 2 ^ i + 1 ) % 3 = 0 where i is in range [ 1 , n ] | C # implementation of the approach ; Function to return the required sum ; Total odd numbers from 1 to n ; Sum of first n odd numbers ; Driver code
using System ; public class GFG { public static int sum ( int n ) { n = ( n + 1 ) / 2 ; return ( n * n ) ; } public static void Main ( string [ ] args ) { int n = 3 ; Console . WriteLine ( sum ( n ) ) ; } }
Numbers that are not divisible by any number in the range [ 2 , 10 ] | C # implementation of the approach ; Function to return the count of numbers from 1 to N which are not divisible by any number in the range [ 2 , 10 ] ; Driver code
using System ; class GFG { static int countNumbers ( int n ) { return n - n / 2 - n / 3 - n / 5 - n / 7 + n / 6 + n / 10 + n / 14 + n / 15 + n / 21 + n / 35 - n / 30 - n / 42 - n / 70 - n / 105 + n / 210 ; } static void Main ( ) { int n = 20 ; Console . WriteLine ( countNumbers ( n ) ) ; } }
Maximum Primes whose sum is equal to given N | C # program for above approach ; Function to find max count of primes ; if n is even n / 2 is required answer if n is odd floor ( n / 2 ) = ( int ) ( n / 2 ) is required answer ; Driver Code
using System ; class GFG { static int maxPrimes ( int n ) { return n / 2 ; } public static void Main ( ) { int n = 17 ; Console . WriteLine ( maxPrimes ( n ) ) ; } }
Sum of the series ( 1 * 2 ) + ( 2 * 3 ) + ( 3 * 4 ) + ... ... upto n terms | C # implementation of the approach ; Function to return sum ; Driver code
using System ; class GFG { static int sum ( int n ) { return n * ( n + 1 ) * ( n + 2 ) / 3 ; } public static void Main ( String [ ] args ) { int n = 2 ; Console . WriteLine ( sum ( n ) ) ; } }
Smallest divisor D of N such that gcd ( D , M ) is greater than 1 | C # implementation of the above approach ; Function to find the minimum divisor ; Iterate for all factors of N ; Check for gcd > 1 ; Check for gcd > 1 ; If gcd is m itself ; Driver code
using System ; class GFG { static int __gcd ( int a , int b ) { if ( b == 0 ) return a ; return __gcd ( b , a % b ) ; } static int findMinimum ( int n , int m ) { int mini = m ; for ( int i = 1 ; i * i <= n ; i ++ ) { if ( n % i == 0 ) { int sec = n / i ; if ( __gcd ( m , i ) > 1 ) { return i ; } else if ( __gcd ( sec , m ) > 1 ) { mini = Math . Min ( sec , mini ) ; } } } if ( mini == m ) return - 1 ; else return mini ; } static void Main ( ) { int n = 8 , m = 10 ; Console . WriteLine ( findMinimum ( n , m ) ) ; } }
Find Nth term of the series 1 , 5 , 32 , 288 ... | C # code to generate ' Nth ' terms of this sequence ; Function to generate a fixed \ number ; Finding nth term ; Driver Method
using System ; class GFG { public static int nthTerm ( int N ) { int nth = 0 , i ; for ( i = N ; i > 0 ; i -- ) { nth += ( int ) Math . Pow ( i , i ) ; } return nth ; } public static void Main ( ) { int N = 3 ; Console . WriteLine ( nthTerm ( N ) ) ; } }
Find kth smallest number in range [ 1 , n ] when all the odd numbers are deleted | C # implementation of the approach ; Function to return the kth smallest element from the range [ 1 , n ] after removing all the odd elements ; Driver code
using System ; class GFG { static int kthSmallest ( int n , int k ) { return ( 2 * k ) ; } public static void Main ( ) { int n = 8 , k = 4 ; Console . WriteLine ( kthSmallest ( n , k ) ) ; } }
Check if a number can be represented as sum of non zero powers of 2 | C # implementation of the approach ; Function that return true if n can be represented as the sum of powers of 2 without using 2 ^ 0 ; Driver code
using System ; class GFG { static bool isSumOfPowersOfTwo ( int n ) { if ( n % 2 == 1 ) return false ; else return true ; } public static void Main ( ) { int n = 10 ; if ( isSumOfPowersOfTwo ( n ) ) Console . WriteLine ( " Yes " ) ; else Console . WriteLine ( " No " ) ; } }
Minimize sum of adjacent difference with removal of one element from array | C # implementation of the approach ; Function to find the element ; Value variable for storing the total value ; Declaring maximum value as zero ; If array contains on element ; Storing the maximum value in temp variable ; Adding the adjacent difference modulus values of removed element . Removing adjacent difference modulus value after removing element ; Returning total value - maximum value ; Driver code
using System ; class GFG { static int findMinRemoval ( int [ ] arr , int n ) { int temp , value = 0 ; int maximum = 0 ; if ( n == 1 ) return 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( i != 0 && i != n - 1 ) { value = value + Math . Abs ( arr [ i ] - arr [ i + 1 ] ) ; temp = Math . Abs ( arr [ i ] - arr [ i + 1 ] ) + Math . Abs ( arr [ i ] - arr [ i - 1 ] ) - Math . Abs ( arr [ i - 1 ] - arr [ i + 1 ] ) ; } else if ( i == 0 ) { value = value + Math . Abs ( arr [ i ] - arr [ i + 1 ] ) ; temp = Math . Abs ( arr [ i ] - arr [ i + 1 ] ) ; } else temp = Math . Abs ( arr [ i ] - arr [ i - 1 ] ) ; maximum = Math . Max ( maximum , temp ) ; } return ( value - maximum ) ; } public static void Main ( ) { int [ ] arr = { 1 , 5 , 3 , 2 , 10 } ; int n = arr . Length ; Console . WriteLine ( findMinRemoval ( arr , n ) ) ; } }
Time until distance gets equal to X between two objects moving in opposite direction | C # implementation of the approach ; Function to return the time for which the two policemen can communicate ; time = distance / speed ; Driver code
using System ; class GFG { static double getTime ( int u , int v , int x ) { double speed = u + v ; double time = x / speed ; return time ; } public static void Main ( ) { int u = 3 , v = 3 , x = 3 ; Console . WriteLine ( getTime ( u , v , x ) ) ; } }
Given number of matches played , find number of teams in tournament | C # implementation of the approach ; Function to return the number of teams ; To store both roots of the equation ; sqrt ( b ^ 2 - 4 ac ) ; First root ( - b + sqrt ( b ^ 2 - 4 ac ) ) / 2 a ; Second root ( - b - sqrt ( b ^ 2 - 4 ac ) ) / 2 a ; Return the positive root ; Driver code
using System ; class GFG { static int number_of_teams ( int M ) { int N1 , N2 , sqr ; sqr = ( int ) Math . Sqrt ( 1 + ( 8 * M ) ) ; N1 = ( 1 + sqr ) / 2 ; N2 = ( 1 - sqr ) / 2 ; if ( N1 > 0 ) return N1 ; return N2 ; } public static void Main ( ) { int M = 45 ; Console . WriteLine ( number_of_teams ( M ) ) ; } }
Sum of numbers from 1 to N which are in Lucas Sequence | C # program to find sum of numbers from 1 to N which are in Lucas Sequence ; Function to return the required sum ; Generate lucas number and keep on adding them ; Driver code
using System ; class GFG { static int LucasSum ( int N ) { int sum = 0 ; int a = 2 , b = 1 , c ; sum += a ; while ( b <= N ) { sum += b ; c = a + b ; a = b ; b = c ; } return sum ; } public static void Main ( String [ ] args ) { int N = 20 ; Console . WriteLine ( LucasSum ( N ) ) ; } }
Count of all even numbers in the range [ L , R ] whose sum of digits is divisible by 3 | C # implementation of the above approach ; Function to return the count of required numbers ; Count of numbers in range which are divisible by 6 ; Driver code
using System ; class GFG { static int countNumbers ( int l , int r ) { return ( ( r / 6 ) - ( l - 1 ) / 6 ) ; } public static void Main ( String [ ] args ) { int l = 1000 , r = 6000 ; Console . WriteLine ( countNumbers ( l , r ) ) ; } }
Sum of minimum element of all sub | C # implementation of the above approach ; Function to find the sum of minimum of all subsequence ; Driver code
using System ; class GFG { static int findMinSum ( int [ ] arr , int n ) { int occ = n - 1 , sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sum += arr [ i ] * ( int ) Math . Pow ( 2 , occ ) ; occ -- ; } return sum ; } public static void Main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 4 , 5 } ; int n = arr . Length ; Console . WriteLine ( findMinSum ( arr , n ) ) ; } }
Number of trailing zeroes in base B representation of N ! | C # program to find the number of trailing zeroes in base B representation of N ! ; To find the power of a prime p in factorial N ; calculating floor ( n / r ) and adding to the count ; increasing the power of p from 1 to 2 to 3 and so on ; returns all the prime factors of k ; vector to store all the prime factors along with their number of occurrence in factorization of B ; Returns largest power of B that divides N ! ; calculating minimum power of all the prime factors of B ; Driver code
using System ; using System . Collections . Generic ; class GFG { public class pair { public int first , second ; public pair ( int first , int second ) { this . first = first ; this . second = second ; } } static int findPowerOfP ( int N , int p ) { int count = 0 ; int r = p ; while ( r <= N ) { count += ( N / r ) ; r = r * p ; } return count ; } static List < pair > primeFactorsofB ( int B ) { List < pair > ans = new List < pair > ( ) ; for ( int i = 2 ; B != 1 ; i ++ ) { if ( B % i == 0 ) { int count = 0 ; while ( B % i == 0 ) { B = B / i ; count ++ ; } ans . Add ( new pair ( i , count ) ) ; } } return ans ; } static int largestPowerOfB ( int N , int B ) { List < pair > vec = new List < pair > ( ) ; vec = primeFactorsofB ( B ) ; int ans = int . MaxValue ; for ( int i = 0 ; i < vec . Count ; i ++ ) ans = Math . Min ( ans , findPowerOfP ( N , vec [ i ] . first ) / vec [ i ] . second ) ; return ans ; } public static void Main ( String [ ] args ) { Console . WriteLine ( largestPowerOfB ( 5 , 2 ) ) ; Console . WriteLine ( largestPowerOfB ( 6 , 9 ) ) ; } }
Count numbers in range 1 to N which are divisible by X but not by Y | C # implementation of the above approach ; Function to count total numbers divisible by x but not y in range 1 to N ; Check if Number is divisible by x but not Y if yes , Increment count ; Driver Code
using System ; class GFG { static int countNumbers ( int X , int Y , int N ) { int count = 0 ; for ( int i = 1 ; i <= N ; i ++ ) { if ( ( i % X == 0 ) && ( i % Y != 0 ) ) count ++ ; } return count ; } public static void Main ( ) { int X = 2 , Y = 3 , N = 10 ; Console . WriteLine ( countNumbers ( X , Y , N ) ) ; } }
Position of a person diametrically opposite on a circle | C # implementation of the approach ; Function to return the required position ; Driver code
using System ; class GFG { static int getPosition ( int n , int m ) { if ( m > ( n / 2 ) ) return ( m - ( n / 2 ) ) ; return ( m + ( n / 2 ) ) ; } static public void Main ( ) { int n = 8 , m = 5 ; Console . WriteLine ( getPosition ( n , m ) ) ; } }
Minimum operations required to modify the array such that parity of adjacent elements is different | C # implementation of the approach ; Function to return the parity of a number ; Function to return the minimum number of operations required ; Operation needs to be performed ; Parity of previous element ; Parity of next element ; Update parity of current element to be other than the parities of the previous and the next number ; Driver Code
using System ; class GFG { static int parity ( int a ) { return a % 3 ; } static int solve ( int [ ] array , int size ) { int operations = 0 ; for ( int i = 0 ; i < size - 1 ; i ++ ) { if ( parity ( array [ i ] ) == parity ( array [ i + 1 ] ) ) { operations ++ ; if ( i + 2 < size ) { int pari1 = parity ( array [ i ] ) ; int pari2 = parity ( array [ i + 2 ] ) ; if ( pari1 == pari2 ) { if ( pari1 == 0 ) array [ i + 1 ] = 1 ; else if ( pari1 == 1 ) array [ i + 1 ] = 0 ; else array [ i + 1 ] = 1 ; } else { if ( ( pari1 == 0 && pari2 == 1 ) || ( pari1 == 1 && pari2 == 0 ) ) array [ i + 1 ] = 2 ; if ( ( pari1 == 1 && pari2 == 2 ) || ( pari1 == 2 && pari2 == 1 ) ) array [ i + 1 ] = 0 ; if ( ( pari1 == 2 && pari2 == 0 ) || ( pari1 == 0 && pari2 == 2 ) ) array [ i + 1 ] = 1 ; } } } } return operations ; } public static void Main ( ) { int [ ] array = { 2 , 1 , 3 , 0 } ; int size = array . Length ; Console . WriteLine ( solve ( array , size ) ) ; } }
Number of submatrices with OR value 1 | C # program to count number of submatrices with OR value 1 ; Function to find required prefix - count for each row from right to left ; Function to find the count of submatrices with OR value 1 ; Array to store prefix count of zeros from right to left for bool array ; Variable to store the count of submatrices with OR value 0 ; Loop to evaluate each column of the prefix matrix uniquely . For each index of a column we will try to determine the number of sub - matrices starting from that index and has all 1 s ; First part of pair will be the value of inserted element . Second part will be the count of the number of elements . Pushed before with a greater value ; Variable to store the number of submatrices with all 0 s ; Return the final answer ; Driver Code
using System ; using System . Collections . Generic ; class GFG { static int n = 3 ; class pair { public int first , second ; public pair ( int first , int second ) { this . first = first ; this . second = second ; } } static void findPrefixCount ( int [ , ] p_arr , bool [ , ] arr ) { for ( int i = 0 ; i < n ; i ++ ) for ( int j = n - 1 ; j >= 0 ; j -- ) { if ( arr [ i , j ] ) continue ; if ( j != n - 1 ) p_arr [ i , j ] += p_arr [ i , j + 1 ] ; p_arr [ i , j ] += ( arr [ i , j ] == false ? 1 : 0 ) ; } } static int matrixOrValueOne ( bool [ , ] arr ) { int [ , ] p_arr = new int [ n , n ] ; findPrefixCount ( p_arr , arr ) ; int count_zero_submatrices = 0 ; for ( int j = 0 ; j < n ; j ++ ) { int i = n - 1 ; Stack < pair > q = new Stack < pair > ( ) ; int to_sum = 0 ; while ( i >= 0 ) { int c = 0 ; while ( q . Count != 0 && q . Peek ( ) . first > p_arr [ i , j ] ) { to_sum -= ( q . Peek ( ) . second + 1 ) * ( q . Peek ( ) . first - p_arr [ i , j ] ) ; c += q . Peek ( ) . second + 1 ; q . Pop ( ) ; } to_sum += p_arr [ i , j ] ; count_zero_submatrices += to_sum ; q . Push ( new pair ( p_arr [ i , j ] , c ) ) ; i -- ; } } return ( n * ( n + 1 ) * n * ( n + 1 ) ) / 4 - count_zero_submatrices ; } public static void Main ( String [ ] args ) { bool [ , ] arr = { { false , false , false } , { false , true , false } , { false , false , false } } ; Console . WriteLine ( matrixOrValueOne ( arr ) ) ; } }
XOR of XORs of all sub | C # program to find the XOR of XOR 's of all submatrices ; Function to find to required XOR value ; Nested loop to find the number of sub - matrix each index belongs to ; Number of ways to choose from top - left elements ; Number of ways to choose from bottom - right elements ; Driver Code
using System ; class GFG { static int submatrixXor ( int [ , ] arr ) { int n = 3 ; int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { int top_left = ( i + 1 ) * ( j + 1 ) ; int bottom_right = ( n - i ) * ( n - j ) ; if ( ( top_left % 2 == 1 ) && ( bottom_right % 2 == 1 ) ) ans = ( ans ^ arr [ i , j ] ) ; } } return ans ; } public static void Main ( ) { int [ , ] arr = { { 6 , 7 , 13 } , { 8 , 3 , 4 } , { 9 , 7 , 6 } } ; Console . Write ( submatrixXor ( arr ) ) ; } }
Find Nth positive number whose digital root is X | C # program to find the N - th number whose digital root is X ; Function to find the digital root of a number ; Function to find the Nth number with digital root as X ; Counter variable to keep the count of valid numbers ; Find digital root ; Check if is required answer or not ; Print the answer if you have found it and breakout of the loop ; Driver Code
using System ; class GFG { static int findDigitalRoot ( int num ) { int sum = int . MaxValue , tempNum = num ; while ( sum >= 10 ) { sum = 0 ; while ( tempNum > 0 ) { sum += tempNum % 10 ; tempNum /= 10 ; } tempNum = sum ; } return sum ; } static void findAnswer ( int X , int N ) { int counter = 0 ; for ( int i = 1 ; counter < N ; ++ i ) { int digitalRoot = findDigitalRoot ( i ) ; if ( digitalRoot == X ) { ++ counter ; } if ( counter == N ) { Console . Write ( i ) ; break ; } } } public static void Main ( String [ ] args ) { int X = 1 , N = 3 ; findAnswer ( X , N ) ; } }
Find Nth positive number whose digital root is X | C # program to find the N - th number with digital root as X ; Function to find the N - th number with digital root as X ; Driver Code
using System ; class GFG { static int findAnswer ( int X , int N ) { return ( N - 1 ) * 9 + X ; } public static void Main ( ) { int X = 7 , N = 43 ; Console . WriteLine ( findAnswer ( X , N ) ) ; } }
Sum of the natural numbers ( up to N ) whose modulo with K yield R | C # implementation of the approach ; Function to return the sum ; If current number gives R as the remainder on dividing by K ; Update the sum ; Return the sum ; Driver code
using System ; class GFG { static long count ( int N , int K , int R ) { long sum = 0 ; for ( int i = 1 ; i <= N ; i ++ ) { if ( i % K == R ) sum += i ; } return sum ; } public static void Main ( ) { int N = 20 , K = 4 , R = 3 ; Console . Write ( count ( N , K , R ) ) ; } }
Longest sub | C # implementation of the approach ; Function to return the length of the longest required sub - sequence ; Find the maximum element from the array ; Insert all lucas numbers below max to the set a and b are first two elements of the Lucas sequence ; If current element is a Lucas number , increment count ; Return the count ; Driver code
using System ; using System . Collections . Generic ; using System . Linq ; class GFG { static int LucasSequence ( int [ ] arr , int n ) { int max = arr . Max ( ) ; int counter = 0 ; HashSet < int > s = new HashSet < int > ( ) ; int a = 2 , b = 1 ; s . Add ( a ) ; s . Add ( b ) ; while ( b < max ) { int c = a + b ; a = b ; b = c ; s . Add ( b ) ; } for ( int i = 0 ; i < n ; i ++ ) { if ( s . Contains ( arr [ i ] ) ) counter ++ ; } return counter ; } static public void Main ( ) { int [ ] arr = { 7 , 11 , 22 , 4 , 2 , 1 , 8 , 9 } ; int n = arr . Length ; Console . WriteLine ( LucasSequence ( arr , n ) ) ; } }
Find the number of solutions to the given equation | C # implementation of the approach ; Function to return the count of valid values of X ; Iterate through all possible sum of digits of X ; Get current value of X for sum of digits i ; Find sum of digits of cr ; If cr is a valid choice for X ; Return the count ; Driver code
using System ; class GFG { static int getCount ( int a , int b , int c ) { int count = 0 ; for ( int i = 1 ; i <= 81 ; i ++ ) { int cr = b * ( int ) Math . Pow ( i , a ) + c ; int tmp = cr ; int sm = 0 ; while ( tmp != 0 ) { sm += tmp % 10 ; tmp /= 10 ; } if ( sm == i && cr < 1e9 ) count ++ ; } return count ; } public static void Main ( ) { int a = 3 , b = 2 , c = 8 ; Console . Write ( getCount ( a , b , c ) ) ; } }
Check if an array of 1 s and 2 s can be divided into 2 parts with equal sum | C # implementation of the above approach : ; Function to check if it is possible to split the array in two parts with equal sum ; Calculate sum of elements and count of 1 's ; If total sum is odd , return False ; If sum of each part is even , return True ; If sum of each part is even but there is atleast one 1 ; Driver Code
using System ; class GFG { static bool isSpiltPossible ( int n , int [ ] a ) { int sum = 0 , c1 = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sum += a [ i ] ; if ( a [ i ] == 1 ) { c1 ++ ; } } if ( sum % 2 != 0 ) return false ; if ( ( sum / 2 ) % 2 == 0 ) return true ; if ( c1 > 0 ) return true ; else return false ; } public static void Main ( ) { int n = 3 ; int [ ] a = { 1 , 1 , 2 } ; if ( isSpiltPossible ( n , a ) ) Console . WriteLine ( " YES " ) ; else Console . WriteLine ( " NO " ) ; } }
Sum of all Submatrices of a Given Matrix | C # program to find the sum of all possible submatrices of a given Matrix ; Function to find the sum of all possible submatrices of a given Matrix ; Varialbe to store the required sum ; Nested loop to find the number of submatrices , each number belongs to ; Number of ways to choose from top - left elements ; Number of ways to choose from bottom - right elements ; Driver Code
using System ; class GFG { static int n = 3 ; static int matrixSum ( int [ , ] arr ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { int top_left = ( i + 1 ) * ( j + 1 ) ; int bottom_right = ( n - i ) * ( n - j ) ; sum += ( top_left * bottom_right * arr [ i , j ] ) ; } } return sum ; } public static void Main ( ) { int [ , ] arr = { { 1 , 1 , 1 } , { 1 , 1 , 1 } , { 1 , 1 , 1 } } ; Console . WriteLine ( matrixSum ( arr ) ) ; } }
Maximum Bitwise AND pair from given range | C # implementation of the approach ; Function to return the maximum bitwise AND possible among all the possible pairs ; Maximum among all ( i , j ) pairs ; Driver code
using System ; class GFG { static int maxAND ( int L , int R ) { int maximum = L & R ; for ( int i = L ; i < R ; i ++ ) for ( int j = i + 1 ; j <= R ; j ++ ) maximum = Math . Max ( maximum , ( i & j ) ) ; return maximum ; } public static void Main ( String [ ] args ) { int L = 1 , R = 632 ; Console . WriteLine ( maxAND ( L , R ) ) ; } }
Split the array into odd number of segments of odd lengths | C # to check whether given array is breakable or not ; Function to check ; Check the result by processing the first & last element and size ; Driver code
using System ; class GFG { static int checkArray ( int [ ] arr , int n ) { return ( ( arr [ 0 ] % 2 ) > 0 && ( arr [ n - 1 ] % 2 ) > 0 && ( n % 2 ) > 0 ) ? 1 : 0 ; } static void Main ( ) { int [ ] arr = { 1 , 2 , 3 , 4 , 5 } ; int n = arr . Length ; Console . WriteLine ( checkArray ( arr , n ) ) ; } }
Minimum removals to make array sum odd | C # implementation of the approach ; Function to find minimum removals ; Count odd numbers ; If the counter is odd return 0 otherwise return 1 ; Driver Code
using System ; class GfG { static int findCount ( int [ ] arr , int n ) { int countOdd = 0 ; for ( int i = 0 ; i < n ; i ++ ) if ( arr [ i ] % 2 == 1 ) countOdd ++ ; if ( countOdd % 2 == 0 ) return 1 ; else return 0 ; } public static void Main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 3 , 5 , 1 } ; int n = arr . Length ; Console . WriteLine ( findCount ( arr , n ) ) ; } }
Check whether the number can be made perfect square after adding 1 | C # implementation of the approach ; Function that returns true if x is a perfect square ; Find floating point value of square root of x ; If square root is an integer ; Function that returns true if n is a sunny number ; If ( n + 1 ) is a perfect square ; Driver code
using System ; class GFG { static bool isPerfectSquare ( double x ) { double sr = Math . Sqrt ( x ) ; return ( ( sr - Math . Floor ( sr ) ) == 0 ) ; } static bool isSunnyNum ( int n ) { if ( isPerfectSquare ( n + 1 ) ) return true ; return false ; } public static void Main ( ) { int n = 3 ; if ( isSunnyNum ( n ) ) Console . WriteLine ( " Yes " ) ; else Console . WriteLine ( " No " ) ; } }
Minimum operations to make counts of remainders same in an array | C # implementation of the above approach ; Function to return the minimum number of operations required ; To store modulos values ; If it 's size greater than k it needed to be decreased ; If it 's size is less than k it needed to be increased ; Driver code
using System ; using System . Collections . Generic ; class GFG { public class pair { public int first , second ; public pair ( int first , int second ) { this . first = first ; this . second = second ; } } static int minOperations ( int n , int [ ] a , int m ) { int k = n / m ; List < int > [ ] val = new List < int > [ m ] ; for ( int i = 0 ; i < val . Length ; i ++ ) val [ i ] = new List < int > ( ) ; for ( int i = 0 ; i < n ; ++ i ) { val [ a [ i ] % m ] . Add ( i ) ; } long ans = 0 ; List < pair > extra = new List < pair > ( ) ; for ( int i = 0 ; i < 2 * m ; ++ i ) { int cur = i % m ; while ( ( val [ cur ] . Count ) > k ) { int elem = val [ cur ] [ val [ cur ] . Count - 1 ] ; val [ cur ] . RemoveAt ( val [ cur ] . Count - 1 ) ; extra . Add ( new pair ( elem , i ) ) ; } while ( val [ cur ] . Count < k && extra . Count != 0 ) { int elem = extra [ extra . Count - 1 ] . first ; int mmod = extra [ extra . Count - 1 ] . second ; extra . RemoveAt ( extra . Count - 1 ) ; val [ cur ] . Add ( elem ) ; ans += i - mmod ; } } return ( int ) ans ; } public static void Main ( String [ ] args ) { int m = 3 ; int [ ] a = { 3 , 2 , 0 , 6 , 10 , 12 } ; int n = a . Length ; Console . Write ( minOperations ( n , a , m ) ) ; } }
Count primes that can be expressed as sum of two consecutive primes and 1 | C # implementation of the approach ; To check if a number is prime or not ; To store possible numbers ; Function to return all prime numbers ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p greater than or equal to the square of it numbers which are multiple of p and are less than p ^ 2 are already been marked . ; Function to count all possible prime numbers that can be expressed as the sum of two consecutive primes and one ; All possible prime numbers below N ; Driver code
using System ; using System . Collections ; class GfG { static int N = 100005 ; static bool [ ] isprime = new bool [ N ] ; static bool [ ] can = new bool [ N ] ; static ArrayList SieveOfEratosthenes ( ) { for ( int a = 0 ; a < N ; a ++ ) { isprime [ a ] = true ; } for ( int p = 2 ; p * p < N ; p ++ ) { if ( isprime [ p ] == true ) { for ( int i = p * p ; i < N ; i += p ) isprime [ i ] = false ; } } ArrayList primes = new ArrayList ( ) ; for ( int i = 2 ; i < N ; i ++ ) if ( isprime [ i ] ) primes . Add ( i ) ; return primes ; } static int Prime_Numbers ( int n ) { ArrayList primes = SieveOfEratosthenes ( ) ; for ( int i = 0 ; i < primes . Count - 1 ; i ++ ) if ( ( int ) primes [ i ] + ( int ) primes [ i + 1 ] + 1 < N ) can [ ( int ) primes [ i ] + ( int ) primes [ i + 1 ] + 1 ] = true ; int ans = 0 ; for ( int i = 2 ; i <= n ; i ++ ) { if ( can [ i ] && isprime [ i ] == true ) { ans ++ ; } } return ans ; } static void Main ( ) { int n = 50 ; Console . WriteLine ( Prime_Numbers ( n ) ) ; } }
Sum of bitwise AND of all subarrays | C # program to find sum of bitwise AND of all subarrays ; Function to find the sum of bitwise AND of all subarrays ; variable to store the final sum ; multiplier ; variable to check if counting is on ; variable to store the length of the subarrays ; loop to find the contiguous segments ; updating the multiplier ; returning the sum ; Driver Code
using System ; class GFG { static int findAndSum ( int [ ] arr , int n ) { int sum = 0 ; int mul = 1 ; for ( int i = 0 ; i < 30 ; i ++ ) { bool count_on = false ; int l = 0 ; for ( int j = 0 ; j < n ; j ++ ) { if ( ( arr [ j ] & ( 1 << i ) ) > 0 ) if ( count_on ) l ++ ; else { count_on = true ; l ++ ; } else if ( count_on ) { sum += ( ( mul * l * ( l + 1 ) ) / 2 ) ; count_on = false ; l = 0 ; } } if ( count_on ) { sum += ( ( mul * l * ( l + 1 ) ) / 2 ) ; count_on = false ; l = 0 ; } mul *= 2 ; } return sum ; } public static void Main ( ) { int [ ] arr = { 7 , 1 , 1 , 5 } ; int n = arr . Length ; Console . Write ( findAndSum ( arr , n ) ) ; } }
Source to destination in 2 | C # implementation of the approach ; Function that returns true if it is possible to move from source to the destination with the given moves ; Driver code
using System ; class GFG { static bool isPossible ( int Sx , int Sy , int Dx , int Dy , int x , int y ) { if ( Math . Abs ( Sx - Dx ) % x == 0 && Math . Abs ( Sy - Dy ) % y == 0 && ( Math . Abs ( Sx - Dx ) / x ) % 2 == ( Math . Abs ( Sy - Dy ) / y ) % 2 ) return true ; return false ; } static void Main ( ) { int Sx = 0 , Sy = 0 , Dx = 0 , Dy = 0 ; int x = 3 , y = 4 ; if ( isPossible ( Sx , Sy , Dx , Dy , x , y ) ) Console . WriteLine ( " Yes " ) ; else Console . WriteLine ( " No " ) ; } }
Count of pairs ( x , y ) in an array such that x < y | C # implementation of the approach ; Function to return the number of pairs ( x , y ) such that x < y ; To store the number of valid pairs ; If a valid pair is found ; Return the count of valid pairs ; Driver code
using System ; class GFG { static int getPairs ( int [ ] a ) { int count = 0 ; for ( int i = 0 ; i < a . Length ; i ++ ) { for ( int j = 0 ; j < a . Length ; j ++ ) { if ( a [ i ] < a [ j ] ) count ++ ; } } return count ; } public static void Main ( ) { int [ ] a = { 2 , 4 , 3 , 1 } ; Console . WriteLine ( getPairs ( a ) ) ; } }
Composite numbers with digit sum 1 | C # implementation of the above approach ; Function that returns true if number n is a composite number ; Corner cases ; This is checked so that we can skip middle five numbers in below loop ; Function that returns true if the eventual digit sum of number nm is 1 ; Loop till the sum is not single digit number ; Intitialize the sum as zero ; Find the sum of digits ; If sum is eventually 1 ; Function to print the required numbers from the given range ; If i is one of the required numbers ; Driver code
using System ; class GFG { static bool isComposite ( int n ) { if ( n <= 1 ) return false ; if ( n <= 3 ) return false ; if ( n % 2 == 0 n % 3 == 0 ) return true ; for ( int i = 5 ; i * i <= n ; i = i + 6 ) if ( n % i == 0 || n % ( i + 2 ) == 0 ) return true ; return false ; } static bool isDigitSumOne ( int nm ) { while ( nm > 9 ) { int sum_digit = 0 ; while ( nm > 0 ) { int digit = nm % 10 ; sum_digit = sum_digit + digit ; nm = nm / 10 ; } nm = sum_digit ; } if ( nm == 1 ) return true ; else return false ; } static void printValidNums ( int l , int r ) { for ( int i = l ; i <= r ; i ++ ) { if ( isComposite ( i ) && isDigitSumOne ( i ) ) Console . Write ( i + " ▁ " ) ; } } static public void Main ( ) { int l = 10 , r = 100 ; printValidNums ( l , r ) ; } }
Determine the count of Leaf nodes in an N | C # program to find number of leaf nodes ; Function to calculate leaf nodes in n - ary tree ; Driver code
using System ; class GFG { static int calcNodes ( int N , int I ) { int result = 0 ; result = I * ( N - 1 ) + 1 ; return result ; } public static void Main ( ) { int N = 5 , I = 2 ; Console . Write ( " Leaf ▁ nodes ▁ = ▁ " + calcNodes ( N , I ) ) ; } }
An application on Bertrand 's ballot theorem | C # implementation of the approach ; Function to calculate factorial of a number mod 1000000007 ; Factorial of i = factorial of ( i - 1 ) * i ; ; Taking mod along with calculation . ; Function for modular exponentiation ; If p is odd ; If p is even ; Function to return the count of required permutations ; Calculating multiplicative modular inverse for x ! and multiplying with ans ; Calculating multiplicative modular inverse for y ! and multiplying with ans ; Driver code ; Pre - compute factorials
class GFG { static long mod = 1000000007 ; static long [ ] arr = new long [ 1000001 ] ; static void cal_factorial ( ) { arr [ 0 ] = 1 ; for ( long i = 1 ; i <= 1000000 ; i ++ ) { arr [ i ] = ( arr [ i - 1 ] * i ) % mod ; } } static long mod_exponent ( long num , long p ) { if ( p == 0 ) return 1 ; if ( ( p & 1 ) != 0 ) { return ( ( num % mod ) * ( mod_exponent ( ( num * num ) % mod , p / 2 ) ) % mod ) % mod ; } else return ( mod_exponent ( ( num * num ) % mod , p / 2 ) ) % mod ; } static long getCount ( long x , long y ) { long ans = arr [ x + y - 1 ] ; ans *= mod_exponent ( arr [ x ] , mod - 2 ) ; ans %= mod ; ans *= mod_exponent ( arr [ y ] , mod - 2 ) ; ans %= mod ; ans *= ( x - y ) ; ans %= mod ; return ans ; } static void Main ( ) { cal_factorial ( ) ; long x = 3 , y = 1 ; System . Console . WriteLine ( getCount ( x , y ) ) ; } }
Find the values of X and Y in the Given Equations | C # program to find the values of X and Y using the given equations ; Function to find the values of X and Y ; base condition ; required answer ; Driver Code
using System ; class GFG { static void findValues ( int a , int b ) { if ( ( a - b ) % 2 == 1 ) { Console . Write ( " - 1" ) ; return ; } Console . WriteLine ( ( ( a - b ) / 2 ) + " ▁ " + ( ( a + b ) / 2 ) ) ; } static public void Main ( ) { int a = 12 , b = 8 ; findValues ( a , b ) ; } }
Program to implement Inverse Interpolation using Lagrange Formula | C # code for solving inverse interpolation ; Consider a structure to keep each pair of x and y together ; Function to calculate the inverse interpolation ; Initialize readonly x ; Calculate each term of the given formula ; Add term to readonly result ; Driver Code ; Sample dataset of 4 points Here we find the value of x when y = 4.5 ; Size of dataset ; Sample y value ; Using the Inverse Interpolation function to find the value of x when y = 4.5
using System ; class GFG { class Data { public double x , y ; public Data ( double x , double y ) { this . x = x ; this . y = y ; } } ; static double inv_interpolate ( Data [ ] d , int n , double y ) { double x = 0 ; int i , j ; for ( i = 0 ; i < n ; i ++ ) { double xi = d [ i ] . x ; for ( j = 0 ; j < n ; j ++ ) { if ( j != i ) { xi = xi * ( y - d [ j ] . y ) / ( d [ i ] . y - d [ j ] . y ) ; } } x += xi ; } return x ; } public static void Main ( String [ ] args ) { Data [ ] d = { new Data ( 1.27 , 2.3 ) , new Data ( 2.25 , 2.95 ) , new Data ( 2.5 , 3.5 ) , new Data ( 3.6 , 5.1 ) } ; int n = 4 ; double y = 4.5 ; Console . Write ( " Value ▁ of ▁ x ▁ at ▁ y ▁ = ▁ 4.5 ▁ : ▁ { 0 : f5 } " , inv_interpolate ( d , n , y ) ) ; } }
Count triplet pairs ( A , B , C ) of points in 2 | C # implementation of the approach ; Function to return the count of possible triplets ; Insert all the points in a set ; If the mid point exists in the set ; Return the count of valid triplets ; Driver code
using System ; using System . Collections . Generic ; class GFG { public class pair { public int first , second ; public pair ( int first , int second ) { this . first = first ; this . second = second ; } } static int countTriplets ( int n , List < pair > points ) { HashSet < pair > pts = new HashSet < pair > ( ) ; int ct = 0 ; for ( int i = 0 ; i < n ; i ++ ) pts . Add ( points [ i ] ) ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = i + 1 ; j < n ; j ++ ) { int x = points [ i ] . first + points [ j ] . first ; int y = points [ i ] . second + points [ j ] . second ; if ( x % 2 == 0 && y % 2 == 0 ) if ( ! pts . Contains ( new pair ( x / 2 , y / 2 ) ) ) ct ++ ; } return ct ; } public static void Main ( String [ ] args ) { List < pair > points = new List < pair > ( ) ; points . Add ( new pair ( 1 , 1 ) ) ; points . Add ( new pair ( 2 , 2 ) ) ; points . Add ( new pair ( 3 , 3 ) ) ; int n = points . Count ; Console . WriteLine ( countTriplets ( n , points ) ) ; } }
Concentration of juice after mixing n glasses in equal proportion | C # implementation of the approach ; Function to return the concentration of the resultant mixture ; Driver code
using System ; class GFG { static double mixtureConcentration ( int n , int [ ] p ) { double res = 0 ; for ( int i = 0 ; i < n ; i ++ ) res += p [ i ] ; res /= n ; return Math . Round ( res , 4 ) ; } static void Main ( ) { int [ ] arr = { 0 , 20 , 20 } ; int n = arr . Length ; Console . WriteLine ( mixtureConcentration ( n , arr ) ) ; } }
Numbers of Length N having digits A and B and whose sum of digits contain only digits A and B | C # implementation of the approach ; Function that returns true if the num contains a and b digits only ; Modular Exponentiation ; Function to return the modular inverse of x modulo MOD ; Function to return the required count of numbers ; Generating factorials of all numbers ; Generating inverse of factorials modulo MOD of all numbers ; Keeping a as largest number ; Iterate over all possible values of s and if it is a valid S then proceed further ; Check for invalid cases in the equation ; Find answer using combinatorics ; Add this result to final answer ; Driver Code
using System ; class GFG { static long MAX = ( long ) ( 1E5 + 5 ) ; static long MOD = ( long ) ( 1E9 + 7 ) ; static bool check ( long num , long a , long b ) { while ( num > 0 ) { long rem = num % 10 ; num /= 10 ; if ( rem != a && rem != b ) return false ; } return true ; } static long power ( long x , long y ) { long ans = 1 ; while ( y > 0 ) { if ( ( y & 1 ) > 0 ) ans = ( ans * x ) % MOD ; y >>= 1 ; x = ( x * x ) % MOD ; } return ans % MOD ; } static long modInverse ( long x ) { return power ( x , MOD - 2 ) ; } static long countNumbers ( long n , long a , long b ) { long [ ] fact = new long [ MAX ] ; long [ ] inv = new long [ MAX ] ; long ans = 0 ; fact [ 0 ] = 1 ; for ( long i = 1 ; i < MAX ; i ++ ) { fact [ i ] = ( 1 * fact [ i - 1 ] * i ) ; fact [ i ] %= MOD ; } inv [ MAX - 1 ] = modInverse ( fact [ MAX - 1 ] ) ; for ( long i = MAX - 2 ; i >= 0 ; i -- ) { inv [ i ] = ( inv [ i + 1 ] * ( i + 1 ) ) ; inv [ i ] %= MOD ; } if ( a < b ) { long x = a ; a = b ; b = x ; } for ( long s = n ; s <= 9 * n ; s ++ ) { if ( ! check ( s , a , b ) ) continue ; if ( s < n * b || ( s - n * b ) % ( a - b ) != 0 ) continue ; long numDig = ( s - n * b ) / ( a - b ) ; if ( numDig > n ) continue ; long curr = fact [ n ] ; curr = ( curr * inv [ numDig ] ) % MOD ; curr = ( curr * inv [ n - numDig ] ) % MOD ; ans = ( ans + curr ) % MOD ; } return ans ; } static void Main ( ) { long n = 3 , a = 1 , b = 3 ; Console . WriteLine ( countNumbers ( n , a , b ) ) ; } }
Number of elements with even factors in the given range | C # implementation of the above approach ; Function to count the perfect squares ; Driver code
using System ; class GFG { static int countOddSquares ( int n , int m ) { return ( int ) Math . Pow ( m , 0.5 ) - ( int ) Math . Pow ( n - 1 , 0.5 ) ; } static public void Main ( ) { int n = 5 , m = 100 ; Console . WriteLine ( " Count ▁ is ▁ " + ( ( m - n + 1 ) - countOddSquares ( n , m ) ) ) ; } }
Total position where king can reach on a chessboard in exactly M moves | C # implementation of above approach ; Function to return the number of squares that the king can reach in the given number of moves ; Calculate initial and final coordinates ; Since chessboard is of size 8 X8 so if any coordinate is less than 1 or greater than 8 make it 1 or 8. ; Calculate total positions ; Driver code
using System ; class GFG { static int Square ( int row , int column , int moves ) { int a = 0 , b = 0 , c = 0 , d = 0 , total = 0 ; a = row - moves ; b = row + moves ; c = column - moves ; d = column + moves ; if ( a < 1 ) a = 1 ; if ( c < 1 ) c = 1 ; if ( b > 8 ) b = 8 ; if ( d > 8 ) d = 8 ; total = ( b - a + 1 ) * ( d - c + 1 ) - 1 ; return total ; } public static void Main ( ) { int R = 4 , C = 5 , M = 2 ; Console . Write ( Square ( R , C , M ) ) ; } }
Find M | C # program to Find m - th number whose sum of digits of a number until sum becomes single digit is N ; Function to find the M - th number whosesum till one digit is N ; Driver Code
using System ; class GFG { static int findNumber ( int n , int m ) { int num = ( m - 1 ) * 9 + n ; return num ; } public static void Main ( ) { int n = 2 , m = 5 ; Console . Write ( findNumber ( n , m ) ) ; } }
Check if a number can be represented as a sum of 2 triangular numbers | C # implementation of the approach ; Function to check if it is possible or not ; Store all triangular numbers up to N in a Set ; Check if a pair exists ; Driver code
using System ; using System . Collections . Generic ; class GFG { static bool checkTriangularSumRepresentation ( int n ) { HashSet < int > tri = new HashSet < int > ( ) ; int i = 1 ; while ( true ) { int x = i * ( i + 1 ) / 2 ; if ( x >= n ) { break ; } tri . Add ( x ) ; i ++ ; } foreach ( int tm in tri ) { if ( tri . Contains ( n - tm ) ) { return true ; } } return false ; } public static void Main ( String [ ] args ) { int n = 24 ; if ( checkTriangularSumRepresentation ( n ) ) { Console . WriteLine ( " Yes " ) ; } else { Console . WriteLine ( " No " ) ; } } }
Absolute difference between the first X and last X Digits of N | C # implementation of the approach ; Function to find the number of digits in the integer ; Function to find the absolute difference ; Store the last x digits in last ; Count the no . of digits in N ; Remove the digits except the first x ; Store the first x digits in first ; Return the absolute difference between the first and last ; Driver code
using System ; class GFG { static int digitsCount ( int n ) { int len = 0 ; while ( n > 0 ) { len ++ ; n /= 10 ; } return len ; } static int absoluteFirstLast ( int n , int x ) { int i = 0 , mod = 1 ; while ( i < x ) { mod *= 10 ; i ++ ; } int last = n % mod ; int len = digitsCount ( n ) ; while ( len != x ) { n /= 10 ; len -- ; } int first = n ; return Math . Abs ( first - last ) ; } public static void Main ( String [ ] args ) { int n = 21546 , x = 2 ; Console . Write ( absoluteFirstLast ( n , x ) ) ; } }
Generate minimum sum sequence of integers with even elements greater | C # implementation of above approach ; Function to print the required sequence ; arr will hold the sequence sum variable will store the sum of the sequence ; If sum of the sequence is odd ; Print the sequence ; Driver Code
using System ; class GFG { public static void make_sequence ( int N ) { int [ ] arr = new int [ N + 1 ] ; int sum = 0 ; for ( int i = 1 ; i <= N ; i ++ ) { if ( i % 2 == 1 ) arr [ i ] = 1 ; else arr [ i ] = 2 ; sum += arr [ i ] ; } if ( sum % 2 == 1 ) arr [ 2 ] = 3 ; for ( int i = 1 ; i <= N ; i ++ ) Console . Write ( arr [ i ] + " ▁ " ) ; } public static void Main ( ) { int N = 9 ; make_sequence ( N ) ; } }