text
stringlengths
17
3.65k
code
stringlengths
60
5.26k
Program to print numbers from N to 1 in reverse order | C # program to print all numbers between 1 to N in reverse order ; Recursive function to print from N to 1 ; Driver code
using System ; class GFG { static void PrintReverseOrder ( int N ) { for ( int i = N ; i > 0 ; i -- ) Console . Write ( i + " ▁ " ) ; } public static void Main ( String [ ] args ) { int N = 5 ; PrintReverseOrder ( N ) ; } }
Find count of numbers from 0 to n which satisfies the given equation for a value K | C # implementation to find the total count of all the numbers from 0 to n which satisfies the given equation for a value K ; Function to find the values ; Calculate the LCM ; Calculate the multiples of lcm ; Find the values which satisfies the given condition ; Subtract the extra values ; Return the readonly result ; Driver code
using System ; class GFG { static int findAns ( int a , int b , int n ) { int lcm = ( a * b ) / __gcd ( a , b ) ; int multiples = ( n / lcm ) + 1 ; int answer = Math . Max ( a , b ) * multiples ; int lastvalue = lcm * ( n / lcm ) + Math . Max ( a , b ) ; if ( lastvalue > n ) { answer = answer - ( lastvalue - n - 1 ) ; } return answer ; } static int __gcd ( int a , int b ) { return b == 0 ? a : __gcd ( b , a % b ) ; } public static void Main ( String [ ] args ) { int a = 1 , b = 13 , n = 500 ; Console . Write ( findAns ( a , b , n ) + " STRNEWLINE " ) ; } }
Program to find if two numbers and their AM and HM are present in an array using STL | C # program to check if two numbers are present in an array then their AM and HM are also present . Finally , find the GM of the numbers ; Function to find the Arithmetic Mean of 2 numbers ; Function to find the Harmonic Mean of 2 numbers ; Following function checks and computes the desired results based on the means ; Calculate means ; Hash container ( Set ) to store elements HashMap < Double , int > Hash = new HashMap < Double , int > ( ) ; ; Insertion of array elements in the Set ; Conditionals to check if numbers are present in array by Hashing ; Conditionals to check if the AM and HM of the numbers are present in array ; If all conditions are satisfied , the Geometric Mean is calculated ; If numbers are found but the respective AM and HM are not found in the array ; If none of the conditions are satisfied ; Driver code
using System ; using System . Collections . Generic ; class GFG { static Double ArithmeticMean ( Double A , Double B ) { return ( A + B ) / 2 ; } static Double HarmonicMean ( Double A , Double B ) { return ( 2 * A * B ) / ( A + B ) ; } static void CheckArithmeticHarmonic ( Double [ ] arr , Double A , Double B , int N ) { Double AM = ArithmeticMean ( A , B ) ; Double HM = HarmonicMean ( A , B ) ; Dictionary < Double , int > Hash = new Dictionary < Double , int > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { Hash [ arr [ i ] ] = 1 ; } if ( Hash . ContainsKey ( A ) && Hash . ContainsKey ( B ) ) { if ( Hash . ContainsKey ( AM ) && Hash . ContainsKey ( HM ) ) { Console . Write ( " GM ▁ = ▁ " ) ; Console . Write ( Math . Round ( Math . Sqrt ( AM * HM ) , 2 ) ) ; } else { Console . WriteLine ( " AM ▁ and ▁ HM ▁ not ▁ found " ) ; } } else { Console . WriteLine ( " numbers ▁ not ▁ found " ) ; } } public static void Main ( ) { Double [ ] arr = { 1.0 , 2.0 , 2.5 , 3.0 , 4.0 , 4.5 , 5.0 , 6.0 } ; int N = ( arr . Length ) ; Double A = 3.0 ; Double B = 6.0 ; CheckArithmeticHarmonic ( arr , A , B , N ) ; } }
Minimum decrements to make integer A divisible by integer B | C # implementation to count total numbers moves to make integer A divisible by integer B ; Function that print number of moves required ; Calculate modulo ; Print the required answer ; Driver code ; Initialise A and B
using System ; class GFG { static void movesRequired ( int a , int b ) { int total_moves = a % b ; Console . Write ( total_moves ) ; } public static void Main ( String [ ] args ) { int A = 10 , B = 3 ; movesRequired ( A , B ) ; } }
Pythagorean Triplet with given sum using single loop | C # program to find the Pythagorean Triplet with given sum ; Function to calculate the Pythagorean triplet in O ( n ) ; Iterate a from 1 to N - 1. ; Calculate value of b ; The value of c = n - a - b ; Driver code ; Function call
using System ; class GFG { static void PythagoreanTriplet ( int n ) { int flag = 0 ; for ( int a = 1 ; a < n ; a ++ ) { int b = ( n * n - 2 * n * a ) / ( 2 * n - 2 * a ) ; int c = n - a - b ; if ( a * a + b * b == c * c && b > 0 && c > 0 ) { Console . Write ( a + " ▁ " + b + " ▁ " + c ) ; flag = 1 ; break ; } } if ( flag == 0 ) { Console . Write ( " - 1" ) ; } return ; } public static void Main ( String [ ] args ) { int N = 12 ; PythagoreanTriplet ( N ) ; } }
Check if there exists a number with X factors out of which exactly K are prime | C # program to check if there exists a number with X factors out of which exactly K are prime ; Function to check if such number exists ; To store the sum of powers of prime factors of X which determines the maximum count of numbers whose product can form X ; Determining the prime factors of X ; To check if the number is prime ; If X is 1 , then we cannot form a number with 1 factor and K prime factor ( as K is atleast 1 ) ; If X itself is prime then it can be represented as a power of only 1 prime factor which is X itself so we return true ; If sum of the powers of prime factors of X is greater than or equal to K , which means X can be represented as a product of K numbers , we return true ; In any other case , we return false as we cannot form a number with X factors and K prime factors ; Driver code
using System ; class GFG { static bool check ( int X , int K ) { int prime , temp , sqr , i ; prime = 0 ; temp = X ; sqr = Convert . ToInt32 ( Math . Sqrt ( X ) ) ; for ( i = 2 ; i <= sqr ; i ++ ) { while ( temp % i == 0 ) { temp = temp / i ; prime ++ ; } } if ( temp > 2 ) prime ++ ; if ( X == 1 ) return false ; if ( prime == 1 && K == 1 ) return true ; else if ( prime >= K ) return true ; else return false ; } static public void Main ( ) { int X , K ; X = 4 ; K = 2 ; if ( check ( X , K ) ) Console . WriteLine ( " Yes " ) ; else Console . WriteLine ( " No " ) ; } }
Print all Coprime path of a Binary Tree | C # program for printing Co - prime paths of binary Tree ; A Tree node ; Utility function to create a new node ; List to store all the prime numbers ; Function to store all the prime numbers in an array ; Create a bool array " prime [ 0 . . N ] " and initialize all the entries in it as true . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p greater than or equal to the square of it numbers which are multiples of p and are less than p ^ 2 are already marked . ; Function to check whether Path is Co - prime or not ; Iterating through the array to find the maximum element in the array ; Incrementing the variable if any of the value has a factor ; If not co - prime ; Function to print a Co - Prime path ; Function to find co - prime paths of binary tree ; Base case ; Store the value in path vector ; Recursively call for left sub tree ; Recursively call for right sub tree ; Condition to check , if leaf node ; Condition to check , if path co - prime or not ; Print co - prime path ; Remove the last element from the path vector ; Function to find Co - Prime paths In a given binary tree ; To save all prime numbers ; Function call ; Driver Code ; Create Binary Tree as shown ; Print Co - Prime Paths
using System ; using System . Collections . Generic ; class GFG { class Node { public int key ; public Node left , right ; } ; static Node newNode ( int key ) { Node temp = new Node ( ) ; temp . key = key ; temp . left = temp . right = null ; return ( temp ) ; } static int N = 1000000 ; static List < int > prime = new List < int > ( ) ; static void SieveOfEratosthenes ( ) { bool [ ] check = new bool [ N + 1 ] ; for ( int i = 0 ; i <= N ; i ++ ) check [ i ] = true ; for ( int p = 2 ; p * p <= N ; p ++ ) { if ( check [ p ] == true ) { prime . Add ( p ) ; for ( int i = p * p ; i <= N ; i += p ) check [ i ] = false ; } } } static bool isPathCo_Prime ( List < int > path ) { int max = 0 ; foreach ( int x in path ) { if ( max < x ) max = x ; } for ( int i = 0 ; i * prime [ i ] <= max / 2 ; i ++ ) { int ct = 0 ; foreach ( int x in path ) { if ( x % prime [ i ] == 0 ) ct ++ ; } if ( ct > 1 ) { return false ; } } return true ; } static void printCo_PrimePaths ( List < int > path ) { foreach ( int x in path ) { Console . Write ( x + " ▁ " ) ; } Console . WriteLine ( ) ; } static void findCo_PrimePaths ( Node root , List < int > path ) { if ( root == null ) return ; path . Add ( root . key ) ; findCo_PrimePaths ( root . left , path ) ; findCo_PrimePaths ( root . right , path ) ; if ( root . left == null && root . right == null ) { if ( isPathCo_Prime ( path ) ) { printCo_PrimePaths ( path ) ; } } path . RemoveAt ( path . Count - 1 ) ; } static void printCo_PrimePaths ( Node node ) { SieveOfEratosthenes ( ) ; List < int > path = new List < int > ( ) ; findCo_PrimePaths ( node , path ) ; } public static void Main ( String [ ] args ) { Node root = newNode ( 10 ) ; root . left = newNode ( 48 ) ; root . right = newNode ( 3 ) ; root . right . left = newNode ( 11 ) ; root . right . right = newNode ( 37 ) ; root . right . left . left = newNode ( 7 ) ; root . right . left . right = newNode ( 29 ) ; root . right . right . left = newNode ( 42 ) ; root . right . right . right = newNode ( 19 ) ; root . right . right . right . left = newNode ( 7 ) ; printCo_PrimePaths ( root ) ; } }
Number of subsets with same AND , OR and XOR values in an Array | C # implementation to find the number of subsets with equal bitwise AND , OR and XOR values ; Function to find the number of subsets with equal bitwise AND , OR and XOR values ; Traverse through all the subsets ; Finding the subsets with the bits of ' i ' which are set ; Computing the bitwise AND ; Computing the bitwise OR ; Computing the bitwise XOR ; Comparing all the three values ; Driver Code
using System ; class GFG { static int mod = 1000000007 ; static int countSubsets ( int [ ] a , int n ) { int answer = 0 ; for ( int i = 0 ; i < ( 1 << n ) ; i ++ ) { int bitwiseAND = - 1 ; int bitwiseOR = 0 ; int bitwiseXOR = 0 ; for ( int j = 0 ; j < n ; j ++ ) { if ( ( i & ( 1 << j ) ) == 0 ) { if ( bitwiseAND == - 1 ) bitwiseAND = a [ j ] ; else bitwiseAND &= a [ j ] ; bitwiseOR |= a [ j ] ; bitwiseXOR ^= a [ j ] ; } } if ( bitwiseAND == bitwiseOR && bitwiseOR == bitwiseXOR ) answer = ( answer + 1 ) % mod ; } return answer ; } public static void Main ( String [ ] args ) { int N = 6 ; int [ ] A = { 1 , 3 , 2 , 1 , 2 , 1 } ; Console . Write ( countSubsets ( A , N ) ) ; } }
Count of Subsets containing only the given value K | C # implementation to find the number of subsets formed by the given value K ; Function to find the number of subsets formed by the given value K ; Count is used to maintain the number of continuous K 's ; Iterating through the array ; If the element in the array is equal to K ; count * ( count + 1 ) / 2 is the total number of subsets with only K as their element ; Change count to 0 because other element apart from K has been found ; To handle the last set of K 's ; Driver code
using System ; class GFG { static int count ( int [ ] arr , int N , int K ) { int count = 0 , ans = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] == K ) { count = count + 1 ; } else { ans += ( count * ( count + 1 ) ) / 2 ; count = 0 ; } } ans = ans + ( count * ( count + 1 ) ) / 2 ; return ans ; } public static void Main ( String [ ] args ) { int [ ] arr = { 1 , 0 , 0 , 1 , 1 , 0 , 0 } ; int N = arr . Length ; int K = 0 ; Console . Write ( count ( arr , N , K ) ) ; } }
Ternary number system or Base 3 numbers | C # program to convert decimal number to ternary number ; Function to convert a decimal number to a ternary number ; Base case ; Finding the remainder when N is divided by 3 ; Recursive function to call the function for the integer division of the value N / 3 ; Handling the negative cases ; Function to convert the decimal to ternary ; If the number is greater than 0 , compute the ternary representation of the number ; Driver Code
using System ; class GFG { static void convertToTernary ( int N ) { if ( N == 0 ) return ; int x = N % 3 ; N /= 3 ; if ( x < 0 ) N += 1 ; convertToTernary ( N ) ; if ( x < 0 ) Console . Write ( x + ( 3 * - 1 ) ) ; else Console . Write ( x ) ; } static void convert ( int Decimal ) { Console . Write ( " Ternary ▁ number ▁ of ▁ " + Decimal + " ▁ is : ▁ " ) ; if ( Decimal != 0 ) { convertToTernary ( Decimal ) ; } else Console . WriteLine ( "0" ) ; } public static void Main ( string [ ] args ) { int Decimal = 2747 ; convert ( Decimal ) ; } }
Largest number less than or equal to Z that leaves a remainder X when divided by Y | C # implementation to Find the largest non - negative number that is less than or equal to integer Z and leaves a remainder X when divided by Y ; Function to get the number ; remainder can ' t ▁ be ▁ larger ▁ ▁ than ▁ the ▁ largest ▁ number , ▁ ▁ if ▁ so ▁ then ▁ answer ▁ doesn ' t exist . ; reduce number by x ; finding the possible number that is divisible by y ; this number is always <= x as we calculated over z - x ; Driver Code ; initialise the three integers
using System ; class GFG { static int get ( int x , int y , int z ) { if ( x > z ) return - 1 ; int val = z - x ; int div = ( z - x ) / y ; int ans = div * y + x ; return ans ; } public static void Main ( String [ ] args ) { int x = 1 , y = 5 , z = 8 ; Console . Write ( get ( x , y , z ) + " STRNEWLINE " ) ; } }
Find the conjugate of a Complex number | C # implementation to find the conjugate of a complex number ; Function to find conjugate of a complex number ; Store index of ' + ' ; Store index of ' - ' ; print the result ; Driver code ; Initialise the complex number
using System ; class GFG { static void solve ( String s ) { String z = s ; int l = s . Length ; int i ; String str ; if ( s . IndexOf ( ' + ' ) != - 1 ) { i = s . IndexOf ( ' + ' ) ; str = s . Replace ( ' + ' , ' - ' ) ; } else { i = s . IndexOf ( ' - ' ) ; str = s . Replace ( ' - ' , ' + ' ) ; } Console . WriteLine ( " Conjugate ▁ of ▁ " + z + " ▁ = ▁ " + str ) ; } public static void Main ( String [ ] args ) { String s = "3-4i " ; solve ( s ) ; } }
Minimum operations required to make two numbers equal | C # program to find minimum operations required to make two numbers equal ; Function to return the minimum operations required ; Keeping B always greater ; Reduce B such that gcd ( A , B ) becomes 1. ; Driver code
using System ; class GFG { static int minOperations ( int A , int B ) { if ( A > B ) { A = A + B ; B = A - B ; A = A - B ; } B = B / __gcd ( A , B ) ; return B - 1 ; } static int __gcd ( int a , int b ) { return b == 0 ? a : __gcd ( b , a % b ) ; } public static void Main ( String [ ] args ) { int A = 7 , B = 15 ; Console . Write ( minOperations ( A , B ) + " STRNEWLINE " ) ; } }
Program to determine the Quadrant of a Complex number | C # program to determine the quadrant of a complex number ; Function to determine the quadrant of a complex number ; Storing the index of ' + ' ; Storing the index of ' - ' ; Finding the real part of the complex number ; Finding the imaginary part of the complex number ; Driver code
using System ; class GFG { static void quadrant ( String s ) { int l = s . Length ; int i ; if ( s . Contains ( " + " ) ) { i = s . IndexOf ( ' + ' ) ; } else { i = s . IndexOf ( ' - ' ) ; } String real = s . Substring ( 0 , i ) ; String imaginary = s . Substring ( i + 1 , l - 2 - i ) ; int x = Int32 . Parse ( real ) ; int y = Int32 . Parse ( imaginary ) ; if ( x > 0 && y > 0 ) Console . Write ( " Quadrant ▁ 1" ) ; else if ( x < 0 && y > 0 ) Console . Write ( " Quadrant ▁ 2" ) ; else if ( x < 0 && y < 0 ) Console . Write ( " Quadrant ▁ 3" ) ; else if ( x > 0 && y < 0 ) Console . Write ( " Quadrant ▁ 4" ) ; else if ( x == 0 && y > 0 ) Console . Write ( " Lies ▁ on ▁ positive " + " ▁ Imaginary ▁ axis " ) ; else if ( x == 0 && y < 0 ) Console . Write ( " Lies ▁ on ▁ negative " + " ▁ Imaginary ▁ axis " ) ; else if ( y == 0 && x < 0 ) Console . Write ( " Lies ▁ on ▁ negative " + " ▁ X - axis " ) ; else if ( y == 0 && x > 0 ) Console . Write ( " Lies ▁ on ▁ positive " + " ▁ X - axis " ) ; else Console . Write ( " Lies ▁ on ▁ the ▁ Origin " ) ; } public static void Main ( String [ ] args ) { String s = "5 + 3i " ; quadrant ( s ) ; } }
Sum and Product of all Fibonacci Nodes of a Singly Linked List | C # implementation to find the sum and product of all of the Fibonacci nodes in a singly linked list ; Node of the singly linked list ; Function to insert a node at the beginning of the singly Linked List ; Allocate new node ; Insert the data ; Link the old list to the new node ; Move the head to point the new node ; Function that returns the largest element from the linked list . ; Declare a max variable and initialize with int . MinValue ; Check loop while head not equal to null ; If max is less then head . data then assign value of head . data to max otherwise node points to next node . ; Function to create a hash table to check Fibonacci numbers ; Inserting the first two numbers in the hash ; Loop to add Fibonacci numbers upto the maximum element present in the linked list ; Function to find the required sum and product ; Find the largest node value in Singly Linked List ; Creating a set containing all the fibonacci numbers upto the maximum data value in the Singly Linked List ; Traverse the linked list ; If current node is fibonacci ; Find the sum and the product ; Driver code ; Create the linked list 15.16 . 8.6 .13
using System ; using System . Collections . Generic ; class GFG { class Node { public int data ; public Node next ; } ; static Node push ( Node head_ref , int new_data ) { Node new_node = new Node ( ) ; new_node . data = new_data ; new_node . next = head_ref ; head_ref = new_node ; return head_ref ; } static int largestElement ( Node head_ref ) { int max = int . MinValue ; Node head = head_ref ; while ( head != null ) { if ( max < head . data ) max = head . data ; head = head . next ; } return max ; } static void createHash ( HashSet < int > hash , int maxElement ) { int prev = 0 , curr = 1 ; hash . Add ( prev ) ; hash . Add ( curr ) ; while ( curr <= maxElement ) { int temp = curr + prev ; hash . Add ( temp ) ; prev = curr ; curr = temp ; } } static void sumAndProduct ( Node head_ref ) { int maxEle = largestElement ( head_ref ) ; HashSet < int > hash = new HashSet < int > ( ) ; createHash ( hash , maxEle ) ; int prod = 1 ; int sum = 0 ; Node ptr = head_ref ; while ( ptr != null ) { if ( hash . Contains ( ptr . data ) ) { prod *= ptr . data ; sum += ptr . data ; } ptr = ptr . next ; } Console . Write ( " Sum ▁ = ▁ " + sum + " STRNEWLINE " ) ; Console . Write ( " Product ▁ = ▁ " + prod ) ; } public static void Main ( String [ ] args ) { Node head = null ; head = push ( head , 13 ) ; head = push ( head , 6 ) ; head = push ( head , 8 ) ; head = push ( head , 16 ) ; head = push ( head , 15 ) ; sumAndProduct ( head ) ; } }
Product of all Subarrays of an Array | C # program to find product of all subarray of an array ; Function to find product of all subarrays ; Variable to store the product ; Compute the product while traversing for subarrays ; Printing product of all subarray ; Driver code ; Function call
using System ; class GFG { static void product_subarrays ( int [ ] arr , int n ) { int product = 1 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i ; j < n ; j ++ ) { for ( int k = i ; k <= j ; k ++ ) product *= arr [ k ] ; } } Console . Write ( product + " STRNEWLINE " ) ; } public static void Main ( String [ ] args ) { int [ ] arr = { 10 , 3 , 7 } ; int n = arr . Length ; product_subarrays ( arr , n ) ; } }
Check if a N base number is Even or Odd | C # code to check if a Octal number is Even or Odd ; To return value of a char . ; Function to convert a number from N base to decimal ; power of base ; Decimal equivalent is str [ len - 1 ] * 1 + str [ len - 1 ] * base + str [ len - 1 ] * ( base ^ 2 ) + ... ; A digit in input number must be less than number 's base ; Returns true if n is even , else odd ; Driver code
using System ; class Gfg { static int val ( char c ) { if ( c >= '0' && c <= '9' ) return ( int ) c - '0' ; else return ( int ) c - ' A ' + 10 ; } static int toDeci ( string str , int base_var ) { int len = str . Length ; int power = 1 ; int num = 0 ; int i ; for ( i = len - 1 ; i >= 0 ; i -- ) { if ( val ( str [ i ] ) >= base_var ) { Console . WriteLine ( " Invalid ▁ Number " ) ; return - 1 ; } num += val ( str [ i ] ) * power ; power = power * base_var ; } return num ; } public static bool isEven ( string num , int N ) { int deci = toDeci ( num , N ) ; return ( deci % 2 == 0 ) ; } public static void Main ( string [ ] args ) { string num = "11A " ; int N = 16 ; if ( isEven ( num , N ) ) { Console . WriteLine ( " Even " ) ; } else { Console . WriteLine ( " Odd " ) ; } } }
Find the next Factorial greater than N | C # implementation of the above approach ; Array that stores the factorial till 20 ; Function to pre - compute the factorial till 20 ; Precomputing factorials ; Function to return the next factorial number greater than N ; Traverse the factorial array ; Find the next just greater factorial than N ; Driver Code ; Function to precalculate the factorial till 20 ; Function call
using System ; class GFG { static int [ ] fact = new int [ 21 ] ; static void preCompute ( ) { fact [ 0 ] = 1 ; for ( int i = 1 ; i < 18 ; i ++ ) fact [ i ] = ( fact [ i - 1 ] * i ) ; } static void nextFactorial ( int N ) { for ( int i = 0 ; i < 21 ; i ++ ) { if ( N < fact [ i ] ) { Console . WriteLine ( fact [ i ] ) ; break ; } } } public static void Main ( string [ ] args ) { preCompute ( ) ; int N = 120 ; nextFactorial ( N ) ; } }
Find K distinct positive odd integers with sum N | C # implementation to find K odd positive integers such that their sum is equal to given number ; Function to find K odd positive integers such that their sum is N ; Condition to check if there are enough values to check ; Driver Code
using System ; public class GFG { static void findDistinctOddSum ( int n , int k ) { if ( ( k * k ) <= n && ( n + k ) % 2 == 0 ) { int val = 1 ; int sum = 0 ; for ( int i = 1 ; i < k ; i ++ ) { Console . Write ( val + " ▁ " ) ; sum += val ; val += 2 ; } Console . Write ( n - sum + " STRNEWLINE " ) ; } else Console . Write ( " NO ▁ STRNEWLINE " ) ; } public static void Main ( String [ ] args ) { int n = 100 ; int k = 4 ; findDistinctOddSum ( n , k ) ; } }
Minimum number of operations to convert array A to array B by adding an integer into a subarray | C # implementation to find the minimum number of operations in which the array A can be converted to another array B ; Function to find the minimum number of operations in which array A can be converted to array B ; Loop to iterate over the array ; if both elements are equal then move to next element ; Calculate the difference between two elements ; loop while the next pair of elements have same difference ; Increase the number of operations by 1 ; Print the number of operations required ; Driver Code
using System ; class GFG { static void checkArray ( int [ ] a , int [ ] b , int n ) { int operations = 0 ; int i = 0 ; while ( i < n ) { if ( a [ i ] - b [ i ] == 0 ) { i ++ ; continue ; } int diff = a [ i ] - b [ i ] ; i ++ ; while ( i < n && a [ i ] - b [ i ] == diff ) { i ++ ; } operations ++ ; } Console . WriteLine ( operations ) ; } public static void Main ( string [ ] args ) { int [ ] a = { 3 , 7 , 1 , 4 , 1 , 2 } ; int [ ] b = { 3 , 7 , 3 , 6 , 3 , 2 } ; int size = a . Length ; checkArray ( a , b , size ) ; } }
Perfect Cube | C # program to check if a number is a perfect cube using prime factors ; Inserts the prime factor in the Hash Map if not present If present updates it 's frequency ; A utility function to find all prime factors of a given number N ; Insert the number of 2 s that divide n ; n must be odd at this point . So we can skip one element ; While i divides n , insert i and divide n ; This condition is to handle the case when n is a prime number greater than 2 ; Function to check if a number is a perfect cube ; Using values ( ) for iteration over keys ; Driver Code ; Function to check if N is perfect cube or not
using System ; using System . Collections . Generic ; public class GFG { public static Dictionary < int , int > insertPF ( Dictionary < int , int > primeFact , int fact ) { if ( primeFact . ContainsKey ( fact ) ) { int freq ; freq = primeFact [ fact ] ; primeFact [ fact ] = ++ freq ; } else { primeFact . Add ( fact , 1 ) ; } return primeFact ; } public static Dictionary < int , int > primeFactors ( int n ) { Dictionary < int , int > primeFact = new Dictionary < int , int > ( ) ; while ( n % 2 == 0 ) { primeFact = insertPF ( primeFact , 2 ) ; n /= 2 ; } for ( int i = 3 ; i <= Math . Sqrt ( n ) ; i += 2 ) { while ( n % i == 0 ) { primeFact = insertPF ( primeFact , i ) ; n /= i ; } } if ( n > 2 ) primeFact = insertPF ( primeFact , n ) ; return primeFact ; } public static String perfectCube ( int n ) { Dictionary < int , int > primeFact ; primeFact = primeFactors ( n ) ; foreach ( int freq in primeFact . Values ) { if ( freq % 3 != 0 ) return " No " ; } return " Yes " ; } public static void Main ( String [ ] args ) { int N = 216 ; Console . WriteLine ( perfectCube ( N ) ) ; } }
Count ways to reach the Nth stair using multiple 1 or 2 steps and a single step 3 | C # implementation to find the number the number of ways to reach Nth stair by taking 1 or 2 steps at a time and 3 rd step exactly once ; Single line to find factorial ; Function to find the number of ways ; Base Case ; Count of 2 - steps ; Count of 1 - steps ; Initial length of sequence ; Expected count of 2 - steps ; Loop to find the ways for every possible sequence ; Driver code
using System ; class GFG { static int factorial ( int n ) { return ( n == 1 n == 0 ) ? 1 : n * factorial ( n - 1 ) ; } static int ways ( int n ) { if ( n < 3 ) { return 0 ; } int c2 = 0 ; int c1 = n - 3 ; int l = c1 + 1 ; int s = 0 ; int exp_c2 = c1 / 2 ; while ( exp_c2 >= c2 ) { int f1 = factorial ( l ) ; int f2 = factorial ( c1 ) ; int f3 = factorial ( c2 ) ; int f4 = ( f2 * f3 ) ; s += f1 / f4 ; c2 += 1 ; c1 -= 2 ; l -= 1 ; } return s ; } static void Main ( ) { int n = 7 ; int ans = ways ( n ) ; Console . WriteLine ( ans ) ; } }
Find N from the value of N ! | C # program to find a number such that the factorial of that number is given ; Map to precompute and store the factorials of the numbers ; Function to precompute factorial ; Calculating the factorial for each i and storing in a map ; Driver code ; Precomputing the factorials
using System ; using System . Collections . Generic ; class GFG { static Dictionary < int , int > m = new Dictionary < int , int > ( ) ; static void precompute ( ) { int fact = 1 ; for ( int i = 1 ; i <= 18 ; i ++ ) { fact = fact * i ; m . Add ( fact , i ) ; } } public static void Main ( String [ ] args ) { precompute ( ) ; int K = 120 ; Console . Write ( m [ K ] + " STRNEWLINE " ) ; K = 6 ; Console . Write ( m [ K ] + " STRNEWLINE " ) ; } }
Count of Leap Years in a given year range | C # implementation to find the count of leap years in given range of the year ; Function to calculate the number of leap years in range of ( 1 , year ) ; Function to calculate the number of leap years in given range ; Driver Code
using System ; class GFG { static int calNum ( int year ) { return ( year / 4 ) - ( year / 100 ) + ( year / 400 ) ; } static void leapNum ( int l , int r ) { l -- ; int num1 = calNum ( r ) ; int num2 = calNum ( l ) ; Console . Write ( num1 - num2 + " STRNEWLINE " ) ; } public static void Main ( String [ ] args ) { int l1 = 1 , r1 = 400 ; leapNum ( l1 , r1 ) ; int l2 = 400 , r2 = 2000 ; leapNum ( l2 , r2 ) ; } }
Ternary representation of Cantor set | C # implementation to find the cantor set for n levels and for a given start_num and end_num ; The Linked List Structure for the Cantor Set ; Function to initialize the Cantor Set List ; Function to propogate the list by adding new nodes for the next levels ; Modifying the start and end values for the next level ; Changing the pointers to the next node ; Recursively call the function to generate the Cantor Set for the entire level ; Function to print a level of the Set ; Function to build and display the Cantor Set for each level ; Driver code
using System ; class GFG { class Cantor { public double start , end ; public Cantor next ; } ; static Cantor cantor ; static Cantor startList ( Cantor head , double start_num , double end_num ) { if ( head == null ) { head = new Cantor ( ) ; head . start = start_num ; head . end = end_num ; head . next = null ; } return head ; } static Cantor propagate ( Cantor head ) { Cantor temp = head ; if ( temp != null ) { Cantor newNode = new Cantor ( ) ; double diff = ( ( ( temp . end ) - ( temp . start ) ) / 3 ) ; newNode . end = temp . end ; temp . end = ( ( temp . start ) + diff ) ; newNode . start = ( newNode . end ) - diff ; newNode . next = temp . next ; temp . next = newNode ; propagate ( temp . next . next ) ; } return head ; } static void print ( Cantor temp ) { while ( temp != null ) { Console . Write ( " [ { 0 : F6 } ] ▁ - - ▁ [ { 1 : F6 } ] " , temp . start , temp . end ) ; temp = temp . next ; } Console . Write ( " STRNEWLINE " ) ; } static void buildCantorSet ( int A , int B , int L ) { Cantor head = null ; head = startList ( head , A , B ) ; for ( int i = 0 ; i < L ; i ++ ) { Console . Write ( " Level _ { 0 } ▁ : ▁ " , i ) ; print ( head ) ; propagate ( head ) ; } Console . Write ( " Level _ { 0 } ▁ : ▁ " , L ) ; print ( head ) ; } public static void Main ( String [ ] args ) { int A = 0 ; int B = 9 ; int L = 2 ; buildCantorSet ( A , B , L ) ; } }
Find sum of f ( s ) for all the chosen sets from the given array | C # implementation of the approach ; To store the factorial and the factorial mod inverse of a number ; Function to find ( a ^ m1 ) % mod ; Function to find factorial of all the numbers ; Function to find the factorial mod inverse of all the numbers ; Function to return nCr ; Function to find sum of f ( s ) for all the chosen sets from the given array ; Sort the given array ; Calculate the factorial and modinverse of all elements ; For all the possible sets Calculate max ( S ) and min ( S ) ; Driver code
using System ; class GFG { static int N = 100005 ; static int mod = 1000000007 ; static int temp = 391657242 ; static int [ ] factorial = new int [ N ] ; static int [ ] modinverse = new int [ N ] ; static int power ( int a , int m1 ) { if ( m1 == 0 ) return 1 ; else if ( m1 == 1 ) return a ; else if ( m1 == 2 ) return ( a * a ) % mod ; else if ( ( m1 & 1 ) != 0 ) return ( a * power ( power ( a , m1 / 2 ) , 2 ) ) % mod ; else return power ( power ( a , m1 / 2 ) , 2 ) % mod ; } static void factorialfun ( ) { factorial [ 0 ] = 1 ; for ( int i = 1 ; i < N ; i ++ ) factorial [ i ] = ( factorial [ i - 1 ] * i ) % mod ; } static void modinversefun ( ) { modinverse [ N - 1 ] = power ( factorial [ N - 1 ] , mod - 2 ) % mod ; for ( int i = N - 2 ; i >= 0 ; i -- ) modinverse [ i ] = ( modinverse [ i + 1 ] * ( i + 1 ) ) % mod ; } static int binomial ( int n , int r ) { if ( r > n ) return 0 ; int a = ( factorial [ n ] * modinverse [ n - r ] ) % mod ; a = ( a * modinverse [ r ] ) % mod ; return a ; } static int max_min ( int [ ] a , int n , int k ) { Array . Sort ( a ) ; factorialfun ( ) ; modinversefun ( ) ; int ans = 0 ; k -- ; for ( int i = 0 ; i < n ; i ++ ) { int x = n - i - 1 ; if ( x >= k ) ans -= binomial ( x , k ) * a [ i ] % mod ; int y = i ; if ( y >= k ) ans += binomial ( y , k ) * a [ i ] % mod ; ans = ( ans + mod ) % mod ; } return ans % temp ; } public static void Main ( string [ ] args ) { int [ ] a = { 1 , 1 , 3 , 4 } ; int k = 2 ; int n = a . Length ; Console . WriteLine ( max_min ( a , n , k ) ) ; } }
Length of Smallest subarray in range 1 to N with sum greater than a given value | C # implementation of the above implementation ; Function to return the count of minimum elements such that the sum of those elements is > S . ; Initialize currentSum = 0 ; Loop from N to 1 to add the numbers and check the condition . ; Driver code
using System ; class GFG { static int countNumber ( int N , int S ) { int countElements = 0 ; int currSum = 0 ; while ( currSum <= S ) { currSum += N ; N -- ; countElements ++ ; } return countElements ; } public static void Main ( ) { int N , S ; N = 5 ; S = 11 ; int count = countNumber ( N , S ) ; Console . WriteLine ( count ) ; } }
Next Number with distinct digits | C # program to find next consecutive Number with all distinct digits ; Function to count distinct digits in a number ; To count the occurrence of digits in number from 0 to 9 ; Iterate over the digits of the number Flag those digits as found in the array ; Traverse the array arr and count the distinct digits in the array ; Function to return the total number of digits in the number ; Iterate over the digits of the number ; Function to return the next number with distinct digits ; Count the distinct digits in N + 1 ; Count the total number of digits in N + 1 ; Return the next consecutive number ; Increment Number by 1 ; Driver code
using System ; class GFG { readonly static int INT_MAX = int . MaxValue ; static int countDistinct ( int n ) { int [ ] arr = new int [ 10 ] ; int count = 0 ; while ( n != 0 ) { int r = n % 10 ; arr [ r ] = 1 ; n /= 10 ; } for ( int i = 0 ; i < 10 ; i ++ ) { if ( arr [ i ] != 0 ) count ++ ; } return count ; } static int countDigit ( int n ) { int c = 0 ; while ( n != 0 ) { int r = n % 10 ; c ++ ; n /= 10 ; } return c ; } static int nextNumberDistinctDigit ( int n ) { while ( n < INT_MAX ) { int distinct_digits = countDistinct ( n + 1 ) ; int total_digits = countDigit ( n + 1 ) ; if ( distinct_digits == total_digits ) { return n + 1 ; } else n ++ ; } return - 1 ; } public static void Main ( String [ ] args ) { int n = 2019 ; Console . WriteLine ( nextNumberDistinctDigit ( n ) ) ; } }
Minimum possible sum of array B such that AiBi = AjBj for all 1 Γ’ ‰€ i < j Γ’ ‰€ N | C # implementation of the approach ; To store least prime factors of all the numbers ; Function to find the least prime factor of all the numbers ; Function to return the ( ( a ^ m1 ) % mod ) ; Function to return the sum of elements of array B ; Find the prime factors of all the numbers ; To store each prime count in lcm ; Current number ; Map to store the prime count of a single number ; Basic way to calculate all prime factors ; If it is the first number in the array ; Take the maximum count of prime in a number ; Calculate lcm of given array ; Calculate sum of elements of array B ; Driver Code
using System ; using System . Collections . Generic ; class GFG { static int mod = 1000000007 ; static int N = 1000005 ; static int [ ] lpf = new int [ N ] ; static void least_prime_factor ( ) { for ( int i = 1 ; i < N ; i ++ ) lpf [ i ] = i ; for ( int i = 2 ; i < N ; i ++ ) if ( lpf [ i ] == i ) for ( int j = i * 2 ; j < N ; j += i ) if ( lpf [ j ] == j ) lpf [ j ] = i ; } static long power ( long a , long m1 ) { if ( m1 == 0 ) return 1 ; else if ( m1 == 1 ) return a ; else if ( m1 == 2 ) return ( a * a ) % mod ; else if ( ( m1 & 1 ) != 0 ) return ( a * power ( power ( a , m1 / 2 ) , 2 ) ) % mod ; else return power ( power ( a , m1 / 2 ) , 2 ) % mod ; } static long sum_of_elements ( long [ ] a , int n ) { least_prime_factor ( ) ; Dictionary < long , long > prime_factor = new Dictionary < long , long > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { long temp = a [ i ] ; Dictionary < long , long > single_number = new Dictionary < long , long > ( ) ; while ( temp > 1 ) { long x = lpf [ ( int ) temp ] ; if ( single_number . ContainsKey ( x ) ) { single_number [ x ] ++ ; } else { single_number [ x ] = 1 ; } temp /= x ; } if ( i == 0 ) prime_factor = single_number ; else { foreach ( KeyValuePair < long , long > ele in single_number ) { if ( prime_factor . ContainsKey ( ele . Key ) ) { prime_factor [ ele . Key ] = Math . Max ( ele . Value , prime_factor [ ele . Key ] ) ; } else { prime_factor [ ele . Key ] = Math . Max ( ele . Value , 0 ) ; } } } } long ans = 0 , lcm = 1 ; foreach ( KeyValuePair < long , long > x in prime_factor ) { lcm = ( lcm * power ( x . Key , x . Value ) ) % mod ; } for ( int i = 0 ; i < n ; i ++ ) ans = ( ans + ( lcm * power ( a [ i ] , mod - 2 ) ) % mod ) % mod ; return ans ; } public static void Main ( string [ ] args ) { long [ ] a = { 2 , 3 , 4 } ; int n = a . Length ; Console . Write ( sum_of_elements ( a , n ) ) ; } }
Find Number of Even cells in a Zero Matrix after Q queries | C # program find Number of Even cells in a Zero Matrix after Q queries ; Function to find the number of even cell in a 2D matrix ; Maintain two arrays , one for rows operation and one for column operation ; Increment operation on row [ i ] ; Increment operation on col [ i ] ; Count odd and even values in both arrays and multiply them ; Count of rows having even numbers ; Count of rows having odd numbers ; Count of columns having even numbers ; Count of columns having odd numbers ; Driver code
using System ; class GFG { static int findNumberOfEvenCells ( int n , int [ , ] q , int size ) { int [ ] row = new int [ n ] ; int [ ] col = new int [ n ] ; for ( int i = 0 ; i < size ; i ++ ) { int x = q [ i , 0 ] ; int y = q [ i , 1 ] ; row [ x - 1 ] ++ ; col [ y - 1 ] ++ ; } int r1 = 0 , r2 = 0 ; int c1 = 0 , c2 = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( row [ i ] % 2 == 0 ) { r1 ++ ; } if ( row [ i ] % 2 == 1 ) { r2 ++ ; } if ( col [ i ] % 2 == 0 ) { c1 ++ ; } if ( col [ i ] % 2 == 1 ) { c2 ++ ; } } int count = r1 * c1 + r2 * c2 ; return count ; } public static void Main ( ) { int n = 2 ; int [ , ] q = { { 1 , 1 } , { 1 , 2 } , { 2 , 1 } } ; int size = q . GetLength ( 0 ) ; Console . WriteLine ( findNumberOfEvenCells ( n , q , size ) ) ; } }
Find maximum unreachable height using two ladders | C # implementation of the approach ; Function to return the maximum height which can 't be reached ; Driver code
using System ; class GFG { static int maxHeight ( int h1 , int h2 ) { return ( ( h1 * h2 ) - h1 - h2 ) ; } public static void Main ( ) { int h1 = 7 , h2 = 5 ; Console . WriteLine ( Math . Max ( 0 , maxHeight ( h1 , h2 ) ) ) ; } }
Fermat 's Factorization Method | C # implementation of fermat 's factorization ; This function finds the value of a and b and returns a + b and a - b ; since fermat 's factorization applicable for odd positive integers only ; check if n is a even number ; if n is a perfect root , then both its square roots are its factors ; Driver Code
using System ; class GFG { static void FermatFactors ( int n ) { if ( n <= 0 ) { Console . Write ( " [ " + n + " ] " ) ; return ; } if ( ( n & 1 ) == 0 ) { Console . Write ( " [ " + n / 2.0 + " , " + 2 + " ] " ) ; return ; } int a = ( int ) Math . Ceiling ( Math . Sqrt ( n ) ) ; if ( a * a == n ) { Console . Write ( " [ " + a + " , " + a + " ] " ) ; return ; } int b ; while ( true ) { int b1 = a * a - n ; b = ( int ) ( Math . Sqrt ( b1 ) ) ; if ( b * b == b1 ) break ; else a += 1 ; } Console . Write ( " [ " + ( a - b ) + " , " + ( a + b ) + " ] " ) ; return ; } public static void Main ( ) { FermatFactors ( 6557 ) ; } }
Append two elements to make the array satisfy the given condition | C # implementation of the approach ; Function to find the required numbers ; Find the sum and xor ; Print the required elements ; Driver code
using System ; class GFG { static void findNums ( int [ ] arr , int n ) { int S = 0 , X = 0 ; for ( int i = 0 ; i < n ; i ++ ) { S += arr [ i ] ; X ^= arr [ i ] ; } Console . WriteLine ( X + " ▁ " + ( X + S ) ) ; } public static void Main ( ) { int [ ] arr = { 1 , 7 } ; int n = arr . Length ; findNums ( arr , n ) ; } }
Satisfy the parabola when point ( A , B ) and the equation is given | C # implementation of the approach ; Function to find the required values ; Driver code
using System ; class GFG { static void solve ( int A , int B ) { double p = B / 2.0 ; double M = Math . Ceiling ( 4 * p ) ; int N = 1 ; int O = - 2 * A ; double Q = Math . Ceiling ( A * A + 4 * p * p ) ; Console . Write ( M + " ▁ " + N + " ▁ " + O + " ▁ " + Q ) ; } static public void Main ( ) { int a = 1 ; int b = 1 ; solve ( a , b ) ; } }
Largest number dividing maximum number of elements in the array | C # implementation of the approach ; Function to return the largest number that divides the maximum elements from the given array ; Finding gcd of all the numbers in the array ; Driver code
using System ; class GFG { static int findLargest ( int [ ] arr , int n ) { int gcd = 0 ; for ( int i = 0 ; i < n ; i ++ ) gcd = __gcd ( arr [ i ] , gcd ) ; return gcd ; } static int __gcd ( int a , int b ) { return b == 0 ? a : __gcd ( b , a % b ) ; } public static void Main ( String [ ] args ) { int [ ] arr = { 3 , 6 , 9 } ; int n = arr . Length ; Console . Write ( findLargest ( arr , n ) ) ; } }
Check if the sum of digits of N is palindrome | C # implementation of the approach ; Function to return the sum of digits of n ; Function that returns true if n is palindrome ; Find the appropriate divisor to extract the leading digit ; If first and last digit not same return false ; Removing the leading and trailing digit from number ; Reducing divisor by a factor of 2 as 2 digits are dropped ; Function that returns true if the digit sum of n is palindrome ; Sum of the digits of n ; If the digit sum is palindrome ; Driver code
using System ; class GFG { static int digitSum ( int n ) { int sum = 0 ; while ( n > 0 ) { sum += ( n % 10 ) ; n /= 10 ; } return sum ; } static bool isPalindrome ( int n ) { int divisor = 1 ; while ( n / divisor >= 10 ) divisor *= 10 ; while ( n != 0 ) { int leading = n / divisor ; int trailing = n % 10 ; if ( leading != trailing ) return false ; n = ( n % divisor ) / 10 ; divisor = divisor / 100 ; } return true ; } static bool isDigitSumPalindrome ( int n ) { int sum = digitSum ( n ) ; if ( isPalindrome ( sum ) ) return true ; return false ; } static public void Main ( ) { int n = 56 ; if ( isDigitSumPalindrome ( n ) ) Console . Write ( " Yes " ) ; else Console . Write ( " No " ) ; } }
Find the value of N XOR 'ed to itself K times | C # implementation of the approach ; Function to return n ^ n ^ ... k times ; If k is odd the answer is the number itself ; Else the answer is 0 ; Driver code
using System ; class GFG { static int xorK ( int n , int k ) { if ( k % 2 == 1 ) return n ; return 0 ; } public static void Main ( String [ ] args ) { int n = 123 , k = 3 ; Console . Write ( xorK ( n , k ) ) ; } }
Find the sum of the costs of all possible arrangements of the cells | C # implementation of the approach ; To store the factorials and factorial mod inverse of the numbers ; Function to return ( a ^ m1 ) % mod ; Function to find the factorials of all the numbers ; Function to find factorial mod inverse of all the numbers ; Function to return nCr ; Function to return the sum of the costs of all the possible arrangements of the cells ; For all possible X 's ; For all possible Y 's ; Driver code
using System ; class GFG { static int N = 20 ; static int mod = 1000000007 ; static int [ ] factorial = new int [ N ] ; static int [ ] modinverse = new int [ N ] ; static int power ( int a , int m1 ) { if ( m1 == 0 ) return 1 ; else if ( m1 == 1 ) return a ; else if ( m1 == 2 ) return ( a * a ) % mod ; else if ( ( m1 & 1 ) != 0 ) return ( a * power ( power ( a , m1 / 2 ) , 2 ) ) % mod ; else return power ( power ( a , m1 / 2 ) , 2 ) % mod ; } static void factorialfun ( ) { factorial [ 0 ] = 1 ; for ( int i = 1 ; i < N ; i ++ ) factorial [ i ] = ( factorial [ i - 1 ] * i ) % mod ; } static void modinversefun ( ) { modinverse [ N - 1 ] = power ( factorial [ N - 1 ] , mod - 2 ) % mod ; for ( int i = N - 2 ; i >= 0 ; i -- ) modinverse [ i ] = ( modinverse [ i + 1 ] * ( i + 1 ) ) % mod ; } static int binomial ( int n , int r ) { if ( r > n ) return 0 ; int a = ( factorial [ n ] * modinverse [ n - r ] ) % mod ; a = ( a * modinverse [ r ] ) % mod ; return a ; } static int arrange ( int n , int m , int k ) { factorialfun ( ) ; modinversefun ( ) ; int ans = 0 ; for ( int i = 1 ; i < n ; i ++ ) ans += ( i * ( n - i ) * m * m ) % mod ; ans = 8 ; for ( int i = 1 ; i < m ; i ++ ) ans += ( i * ( m - i ) * n * n ) % mod ; ans = ( ans * binomial ( n * m - 2 , k - 2 ) ) % mod + 8 ; return ans ; } public static void Main ( String [ ] args ) { int n = 2 , m = 2 , k = 2 ; Console . WriteLine ( arrange ( n , m , k ) ) ; } }
Find the Nth digit in the proper fraction of two numbers | C # implementation of the approach ; Function to print the Nth digit in the fraction ( p / q ) ; To store the resultant digit ; While N > 0 compute the Nth digit by dividing p and q and store the result into variable res and go to next digit ; Driver code
using System ; class GFG { static int findNthDigit ( int p , int q , int N ) { int res = 0 ; while ( N > 0 ) { N -- ; p *= 10 ; res = p / q ; p %= q ; } return res ; } public static void Main ( ) { int p = 1 , q = 2 , N = 1 ; Console . WriteLine ( findNthDigit ( p , q , N ) ) ; } }
Sum of the updated array after performing the given operation | C # implementation of the approach ; Utility function to return the sum of the array ; Function to return the sum of the modified array ; Subtract the subarray sum ; Sum of subarray arr [ i ... n - 1 ] ; Return the sum of the modified array ; Driver code
using System ; class GFG { static int sumArr ( int [ ] arr , int n ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) sum += arr [ i ] ; return sum ; } static int sumModArr ( int [ ] arr , int n ) { int subSum = arr [ n - 1 ] ; for ( int i = n - 2 ; i >= 0 ; i -- ) { int curr = arr [ i ] ; arr [ i ] -= subSum ; subSum += curr ; } return sumArr ( arr , n ) ; } public static void Main ( String [ ] args ) { int [ ] arr = { 40 , 25 , 12 , 10 } ; int n = arr . Length ; Console . WriteLine ( sumModArr ( arr , n ) ) ; } }
Find closest integer with the same weight | C # implementation of the approach ; Function to return the number closest to x which has equal number of set bits as x ; Loop for each bit in x and compare with the next bit ; Driver code
using System ; class GFG { static int NumUnsignBits = 64 ; static long findNum ( long x ) { for ( int i = 0 ; i < NumUnsignBits - 1 ; i ++ ) { if ( ( ( x >> i ) & 1 ) != ( ( x >> ( i + 1 ) ) & 1 ) ) { x ^= ( 1 << i ) | ( 1 << ( i + 1 ) ) ; return x ; } } return long . MinValue ; } public static void Main ( String [ ] args ) { int n = 92 ; Console . WriteLine ( findNum ( n ) ) ; } }
Cake Distribution Problem | C # implementation of the approach ; Function to return the remaining count of cakes ; Sum for 1 cycle ; no . of full cycle and remainder ; Driver Code
using System ; class GFG { static int cntCakes ( int n , int m ) { int sum = ( n * ( n + 1 ) ) / 2 ; int quo = m / sum ; int rem = m % sum ; double ans = m - quo * sum ; double x = ( - 1 + Math . Pow ( ( 8 * rem ) + 1 , 0.5 ) ) / 2 ; ans = ans - x * ( x + 1 ) / 2 ; return ( int ) ans ; } static public void Main ( ) { int n = 3 ; int m = 8 ; int ans = cntCakes ( n , m ) ; Console . Write ( ans ) ; } }
Find the number of squares inside the given square grid | C # implementation of the approach ; Function to return the number of squares inside an n * n grid ; Driver code
using System ; class GFG { static int cntSquares ( int n ) { return n * ( n + 1 ) * ( 2 * n + 1 ) / 6 ; } public static void Main ( String [ ] args ) { Console . Write ( cntSquares ( 4 ) ) ; } }
Find all palindrome numbers of given digits | C # implementation of the approach ; Function to return the reverse of num ; Function that returns true if num is palindrome ; If the number is equal to the reverse of it then it is a palindrome ; Function to print all the d - digit palindrome numbers ; Smallest and the largest d - digit numbers ; Starting from the smallest d - digit number till the largest ; If the current number is palindrome ; Driver code
using System ; class GFG { static int reverse ( int num ) { int rev = 0 ; while ( num > 0 ) { rev = rev * 10 + num % 10 ; num = num / 10 ; } return rev ; } static bool isPalindrome ( int num ) { if ( num == reverse ( num ) ) return true ; return false ; } static void printPalindromes ( int d ) { if ( d <= 0 ) return ; int smallest = ( int ) Math . Pow ( 10 , d - 1 ) ; int largest = ( int ) Math . Pow ( 10 , d ) - 1 ; for ( int i = smallest ; i <= largest ; i ++ ) { if ( isPalindrome ( i ) ) Console . Write ( i + " ▁ " ) ; } } public static void Main ( String [ ] args ) { int d = 2 ; printPalindromes ( d ) ; } }
Find X and Y intercepts of a line passing through the given points | C # implementation of the approach ; Function to find the X and Y intercepts of the line passing through the given points ; if line is parallel to y axis ; x - intercept will be p [ 0 ] ; y - intercept will be infinity ; if line is parallel to x axis ; x - intercept will be infinity ; y - intercept will be p [ 1 ] ; Slope of the line ; y = mx + c in where c is unknown Use any of the given point to find c ; For finding the x - intercept put y = 0 ; For finding the y - intercept put x = 0 ; Driver code
using System ; class GFG { static void getXandYintercept ( int [ ] P , int [ ] Q ) { int a = P [ 1 ] - Q [ 1 ] ; int b = P [ 0 ] - Q [ 0 ] ; if ( b == 0 ) { Console . WriteLine ( P [ 0 ] ) ; Console . WriteLine ( " infinity " ) ; return ; } if ( a == 0 ) { Console . WriteLine ( " infinity " ) ; Console . WriteLine ( P [ 1 ] ) ; return ; } double m = a / ( b * 1.0 ) ; int x = P [ 0 ] ; int y = P [ 1 ] ; double c = y - m * x ; y = 0 ; double r = ( y - c ) / ( m * 1.0 ) ; Console . WriteLine ( r ) ; x = 0 ; y = ( int ) ( m * x + c ) ; Console . WriteLine ( c ) ; } public static void Main ( ) { int [ ] p1 = { 5 , 2 } ; int [ ] p2 = { 2 , 7 } ; getXandYintercept ( p1 , p2 ) ; } }
Minimum number of moves to reach N starting from ( 1 , 1 ) | C # implementation of the approach ; Function to return the minimum number of moves required to reach the cell containing N starting from ( 1 , 1 ) ; To store the required answer ; For all possible values of divisors ; If i is a divisor of n ; Get the moves to reach n ; Return the required answer ; Driver code
using System ; class GFG { static int min_moves ( int n ) { int ans = int . MaxValue ; for ( int i = 1 ; i * i <= n ; i ++ ) { if ( n % i == 0 ) { ans = Math . Min ( ans , i + n / i - 2 ) ; } } return ans ; } public static void Main ( String [ ] args ) { int n = 10 ; Console . WriteLine ( min_moves ( n ) ) ; } }
Minimum possible value of ( i * j ) % 2019 | C # implementation of the approach ; Function to return the minimum possible value of ( i * j ) % 2019 ; If we can get a number divisible by 2019 ; Find the minimum value by running nested loops ; Driver code
using System ; class GFG { static int MOD = 2019 ; static int min_modulo ( int l , int r ) { if ( r - l >= MOD ) return 0 ; else { int ans = MOD - 1 ; for ( int i = l ; i <= r ; i ++ ) { for ( int j = i + 1 ; j <= r ; j ++ ) { ans = Math . Min ( ans , ( i * j ) % MOD ) ; } } return ans ; } } public static void Main ( String [ ] args ) { int l = 2020 , r = 2040 ; Console . WriteLine ( min_modulo ( l , r ) ) ; } }
Represent ( 2 / N ) as the sum of three distinct positive integers of the form ( 1 / m ) | C # implementation of the approach ; Function to find the required fractions ; Base condition ; For N > 1 ; Driver code
using System ; class GFG { static void find_numbers ( int N ) { if ( N == 1 ) { Console . Write ( - 1 ) ; } else { Console . Write ( N + " ▁ " + ( N + 1 ) + " ▁ " + ( N * ( N + 1 ) ) ) ; } } public static void Main ( String [ ] args ) { int N = 5 ; find_numbers ( N ) ; } }
Count the pairs in an array such that the difference between them and their indices is equal | C # implementation of the approach ; Function to return the count of all valid pairs ; To store the frequencies of ( arr [ i ] - i ) ; To store the required count ; If cnt is the number of elements whose difference with their index is same then ( ( cnt * ( cnt - 1 ) ) / 2 ) such pairs are possible ; Driver code
using System ; using System . Collections . Generic ; class GFG { static int countPairs ( int [ ] arr , int n ) { Dictionary < int , int > map = new Dictionary < int , int > ( ) ; for ( int i = 0 ; i < n ; i ++ ) map [ arr [ i ] - i ] = 0 ; for ( int i = 0 ; i < n ; i ++ ) map [ arr [ i ] - i ] ++ ; int res = 0 ; foreach ( KeyValuePair < int , int > x in map ) { int cnt = x . Value ; res += ( ( cnt * ( cnt - 1 ) ) / 2 ) ; } return res ; } public static void Main ( String [ ] args ) { int [ ] arr = { 1 , 5 , 6 , 7 , 9 } ; int n = arr . Length ; Console . WriteLine ( countPairs ( arr , n ) ) ; } }
Minimum possible number with the given operation | C # implementation of the above approach ; Function to return the minimum possible integer that can be obtained from the given integer after performing the given operations ; For every digit ; Digits less than 5 need not to be changed as changing them will lead to a larger number ; The resulting integer cannot have leading zero ; Driver code
using System ; class GFG { static string minInt ( char [ ] str ) { for ( int i = 0 ; i < str . Length ; i ++ ) { if ( ( int ) str [ i ] >= ( int ) ( '5' ) ) { str [ i ] = ( char ) ( ( ( int ) ( '9' ) - ( int ) ( str [ i ] ) ) + ( int ) ( '0' ) ) ; } } if ( str [ 0 ] == '0' ) str [ 0 ] = '9' ; string s = new string ( str ) ; return s ; } static public void Main ( ) { string str = "589" ; Console . WriteLine ( minInt ( str . ToCharArray ( ) ) ) ; } }
Reduce N to 1 with minimum number of given operations | C # implementation of the approach ; Function to return the minimum number of given operations required to reduce n to 1 ; To store the count of operations ; To store the digit ; If n is already then no operation is required ; Extract all the digits except the first digit ; Store the maximum of that digits ; for each digit ; First digit ; Add the value to count ; Driver code
using System ; class GFG { static long minOperations ( long n ) { long count = 0 ; long d = 0 ; if ( n == 1 ) return 0 ; while ( n > 9 ) { d = Math . Max ( n % 10 , d ) ; n /= 10 ; count += 10 ; } d = Math . Max ( d , n - 1 ) ; count += Math . Abs ( d ) ; return count - 1 ; } public static void Main ( String [ ] args ) { long n = 240 ; Console . WriteLine ( minOperations ( n ) ) ; } }
Find the largest number that can be formed by changing at most K digits | C # implementation of the approach ; Function to return the maximum number that can be formed by changing at most k digits in str ; For every digit of the number ; If no more digits can be replaced ; If current digit is not already 9 ; Replace it with 9 ; One digit has been used ; Driver code
using System ; using System . Text ; class GFG { static StringBuilder findMaximumNum ( StringBuilder str , int n , int k ) { for ( int i = 0 ; i < n ; i ++ ) { if ( k < 1 ) break ; if ( str [ i ] != '9' ) { str [ i ] = '9' ; k -- ; } } return str ; } public static void Main ( ) { StringBuilder str = new StringBuilder ( "569431" ) ; int n = str . Length ; int k = 3 ; Console . WriteLine ( findMaximumNum ( str , n , k ) ) ; } }
Number of occurrences of a given angle formed using 3 vertices of a n | C # implementation of the approach ; Function that calculates occurrences of given angle that can be created using any 3 sides ; Maximum angle in a regular n - gon is equal to the interior angle If the given angle is greater than the interior angle then the given angle cannot be created ; The given angle times n should be divisible by 180 else it cannot be created ; Initialise answer ; Calculate the frequency of given angle for each vertex ; Multiply answer by frequency . ; Multiply answer by the number of vertices . ; Driver code
using System ; class GFG { static int solve ( int ang , int n ) { if ( ( ang * n ) > ( 180 * ( n - 2 ) ) ) { return 0 ; } else if ( ( ang * n ) % 180 != 0 ) { return 0 ; } int ans = 1 ; int freq = ( ang * n ) / 180 ; ans = ans * ( n - 1 - freq ) ; ans = ans * n ; return ans ; } public static void Main ( String [ ] args ) { int ang = 90 , n = 4 ; Console . WriteLine ( solve ( ang , n ) ) ; } }
Find third number such that sum of all three number becomes prime | C # implementation of the above approach ; Function that will check whether number is prime or not ; Function to print the 3 rd number ; If the sum is odd ; If sum is not prime ; Driver code
using System ; class GFG { static bool prime ( int n ) { for ( int i = 2 ; i * i <= n ; i ++ ) { if ( n % i == 0 ) return false ; } return true ; } static void thirdNumber ( int a , int b ) { int sum = 0 , temp = 0 ; sum = a + b ; temp = 1 ; if ( sum == 0 ) { temp = 2 ; } while ( ! prime ( sum + temp ) ) { temp += 2 ; } Console . Write ( temp ) ; } static public void Main ( ) { int a = 3 , b = 5 ; thirdNumber ( a , b ) ; } }
Total ways of selecting a group of X men from N men with or without including a particular man | C # implementation of the approach ; Function to return the value of nCr ; Initialize the answer ; Divide simultaneously by i to avoid overflow ; Function to return the count of ways ; Driver code
using System ; class GFG { static int nCr ( int n , int r ) { int ans = 1 ; for ( int i = 1 ; i <= r ; i += 1 ) { ans *= ( n - r + i ) ; ans /= i ; } return ans ; } static int total_ways ( int N , int X ) { return ( nCr ( N - 1 , X - 1 ) + nCr ( N - 1 , X ) ) ; } public static void Main ( String [ ] args ) { int N = 5 , X = 3 ; Console . WriteLine ( total_ways ( N , X ) ) ; } }
Compute the maximum power with a given condition | C # program for Compute maximum power to which K can be raised so that given condition remains true ; Function to return the largest power ; If n is greater than given M ; If n == m ; Checking for the next power ; Driver Code
using System ; class GFG { static int calculate ( int n , int k , int m , int power ) { if ( n > m ) { if ( power == 0 ) return 0 ; else return power - 1 ; } else if ( n == m ) return power ; else return calculate ( n * k , k , m , power + 1 ) ; } public static void Main ( String [ ] args ) { int N = 1 , K = 2 , M = 5 ; Console . WriteLine ( calculate ( N , K , M , 0 ) ) ; } }
Program to find the number from given holes | C # implementation of the above approach ; Function that will find out the number ; If number of holes equal 0 then return 1 ; If number of holes equal 0 then return 0 ; If number of holes is more than 0 or 1. ; If number of holes is odd ; Driver code ; Calling Function
using System ; class GFG { static void printNumber ( int holes ) { if ( holes == 0 ) Console . Write ( "1" ) ; else if ( holes == 1 ) Console . Write ( "0" ) ; else { int rem = 0 , quo = 0 ; rem = holes % 2 ; quo = holes / 2 ; if ( rem == 1 ) Console . Write ( "4" ) ; for ( int i = 0 ; i < quo ; i ++ ) Console . Write ( "8" ) ; } } static public void Main ( ) { int holes = 3 ; printNumber ( holes ) ; } }
Minimum cost to make all array elements equal | C # implementation of the approach ; Function to return the minimum cost to make each array element equal ; To store the count of even numbers present in the array ; To store the count of odd numbers present in the array ; Iterate through the array and find the count of even numbers and odd numbers ; Driver code
using System ; class GFG { static int minCost ( int [ ] arr , int n ) { int count_even = 0 ; int count_odd = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] % 2 == 0 ) count_even ++ ; else count_odd ++ ; } return Math . Min ( count_even , count_odd ) ; } public static void Main ( String [ ] args ) { int [ ] arr = { 2 , 4 , 3 , 1 , 5 } ; int n = arr . Length ; Console . WriteLine ( minCost ( arr , n ) ) ; } }
Number of Subarrays with positive product | C # implementation of the approach ; Function to return the count of subarrays with negative product ; Replace current element with 1 if it is positive else replace it with - 1 instead ; Take product with previous element to form the prefix product ; Count positive and negative elements in the prefix product array ; Return the required count of subarrays ; Function to return the count of subarrays with positive product ; Total subarrays possible ; Count to subarrays with negative product ; Return the count of subarrays with positive product ; Driver code
using System ; class GFG { static int negProdSubArr ( int [ ] arr , int n ) { int positive = 1 , negative = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] > 0 ) arr [ i ] = 1 ; else arr [ i ] = - 1 ; if ( i > 0 ) arr [ i ] *= arr [ i - 1 ] ; if ( arr [ i ] == 1 ) positive ++ ; else negative ++ ; } return ( positive * negative ) ; } static int posProdSubArr ( int [ ] arr , int n ) { int total = ( n * ( n + 1 ) ) / 2 ; int cntNeg = negProdSubArr ( arr , n ) ; return ( total - cntNeg ) ; } public static void Main ( String [ ] args ) { int [ ] arr = { 5 , - 4 , - 3 , 2 , - 5 } ; int n = arr . Length ; Console . WriteLine ( posProdSubArr ( arr , n ) ) ; } }
Find the XOR of first N Prime Numbers | C # implementation of the approach ; 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 ; Function to return the xor of 1 st N prime numbers ; Count of prime numbers ; XOR of prime numbers ; If the number is prime xor it ; Increment the count ; Get to the next number ; Driver code ; Create the sieve ; Find the xor of 1 st n prime numbers
using System ; class GFG { static int MAX = 10000 ; static bool [ ] prime = new bool [ MAX + 1 ] ; static void SieveOfEratosthenes ( ) { int i ; for ( i = 0 ; i < MAX + 1 ; i ++ ) { prime [ i ] = true ; } prime [ 1 ] = false ; for ( int p = 2 ; p * p <= MAX ; p ++ ) { if ( prime [ p ] == true ) { for ( i = p * 2 ; i <= MAX ; i += p ) prime [ i ] = false ; } } } static int xorFirstNPrime ( int n ) { int count = 0 , num = 1 ; int xorVal = 0 ; while ( count < n ) { if ( prime [ num ] ) { xorVal ^= num ; count ++ ; } num ++ ; } return xorVal ; } static public void Main ( ) { SieveOfEratosthenes ( ) ; int n = 4 ; Console . Write ( xorFirstNPrime ( n ) ) ; } }
Sum of all natural numbers from L to R ( for large values of L and R ) | C # implementation of the approach ; Value of inverse modulo 2 with 10 ^ 9 + 7 ; Function to return num % 1000000007 where num is a large number ; Initialize result ; One by one process all the digits of string ' num ' ; Function to return the sum of the longegers from the given range modulo 1000000007 ; a stores the value of L modulo 10 ^ 9 + 7 ; b stores the value of R modulo 10 ^ 9 + 7 ; l stores the sum of natural numbers from 1 to ( a - 1 ) ; r stores the sum of natural numbers from 1 to b ; If the result is negative ; Driver code
using System ; class GFG { static long mod = 1000000007 ; static long inv2 = 500000004 ; static long modulo ( String num ) { long res = 0 ; for ( int i = 0 ; i < num . Length ; i ++ ) res = ( res * 10 + ( long ) num [ i ] - '0' ) % mod ; return res ; } static long findSum ( String L , String R ) { long a , b , l , r , ret ; a = modulo ( L ) ; b = modulo ( R ) ; l = ( ( a * ( a - 1 ) ) % mod * inv2 ) % mod ; r = ( ( b * ( b + 1 ) ) % mod * inv2 ) % mod ; ret = ( r % mod - l % mod ) ; if ( ret < 0 ) ret = ret + mod ; else ret = ret % mod ; return ret ; } public static void Main ( String [ ] args ) { String L = "88949273204" ; String R = "98429729474298592" ; Console . WriteLine ( findSum ( L , R ) ) ; } }
Maximum subsequence sum such that all elements are K distance apart | C # implementation of the approach ; Function to return the maximum subarray sum for the array { a [ i ] , a [ i + k ] , a [ i + 2 k ] , ... } ; Function to return the sum of the maximum required subsequence ; To store the result ; Run a loop from 0 to k ; Find the maximum subarray sum for the array { a [ i ] , a [ i + k ] , a [ i + 2 k ] , ... } ; Return the maximum value ; Driver code
using System ; class GFG { static int maxSubArraySum ( int [ ] a , int n , int k , int i ) { int max_so_far = int . MinValue , max_ending_here = 0 ; while ( i < n ) { max_ending_here = max_ending_here + a [ i ] ; if ( max_so_far < max_ending_here ) max_so_far = max_ending_here ; if ( max_ending_here < 0 ) max_ending_here = 0 ; i += k ; } return max_so_far ; } static int find ( int [ ] arr , int n , int k ) { int maxSum = 0 ; for ( int i = 0 ; i <= Math . Min ( n , k ) ; i ++ ) { maxSum = Math . Max ( maxSum , maxSubArraySum ( arr , n , k , i ) ) ; } return maxSum ; } public static void Main ( ) { int [ ] arr = { 2 , - 3 , - 1 , - 1 , 2 } ; int n = arr . Length ; int k = 2 ; Console . WriteLine ( find ( arr , n , k ) ) ; } }
Generate N integers satisfying the given conditions | C # implementation of the above approach ; 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 ; Function to find the first n odd prime numbers ; To store the current count of prime numbers ; Starting with 3 as 2 is an even prime number ; If i is prime ; Print i and increment count ; Driver code ; Create the sieve
using System ; class GFG { static int MAX = 1000000 ; static bool [ ] prime = new bool [ MAX + 1 ] ; static void SieveOfEratosthenes ( ) { for ( int i = 0 ; i <= MAX ; i ++ ) prime [ i ] = true ; 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 ; } } } static void solve ( int n ) { int count = 0 ; for ( int i = 3 ; count < n ; i ++ ) { if ( prime [ i ] ) { Console . Write ( i + " ▁ " ) ; count ++ ; } } } public static void Main ( String [ ] args ) { SieveOfEratosthenes ( ) ; int n = 6 ; solve ( n ) ; } }
Probability that a N digit number is palindrome | C # implementation of the approach ; Find the probability that a n digit number is palindrome ; Denominator ; Assign 10 ^ ( floor ( n / 2 ) ) to denominator ; Display the answer ; Driver code
using System ; class GFG { static void solve ( int n ) { int n_2 = n / 2 ; String den ; den = "1" ; while ( n_2 -- > 0 ) den += '0' ; Console . WriteLine ( 1 + " / " + den ) ; } public static void Main ( String [ ] args ) { int N = 5 ; solve ( N ) ; } }
Ways to choose balls such that at least one ball is chosen | C # implementation of the approach ; Function to return the count of ways to choose the balls ; Calculate ( 2 ^ n ) % MOD ; Subtract the only where no ball was chosen ; Driver code
using System ; class GFG { static int MOD = 1000000007 ; static int countWays ( int n ) { int ans = 1 ; for ( int i = 0 ; i < n ; i ++ ) { ans *= 2 ; ans %= MOD ; } return ( ( ans - 1 + MOD ) % MOD ) ; } public static void Main ( String [ ] args ) { int n = 3 ; Console . WriteLine ( countWays ( n ) ) ; } }
Minimize the sum of the array according the given condition | C # implementation of the above approach ; Function to return the minimum sum ; sort the array to find the minimum element ; finding the number to divide ; Checking to what instance the sum has decreased ; getting the max difference ; Driver Code
using System ; class GFG { static void findMin ( int [ ] arr , int n ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) sum += arr [ i ] ; Array . Sort ( arr ) ; int min = arr [ 0 ] ; int max = 0 ; for ( int i = n - 1 ; i >= 1 ; i -- ) { int num = arr [ i ] ; int total = num + min ; int j ; for ( j = 2 ; j <= num ; j ++ ) { if ( num % j == 0 ) { int d = j ; int now = ( num / d ) + ( min * d ) ; int reduce = total - now ; if ( reduce > max ) max = reduce ; } } } Console . WriteLine ( sum - max ) ; } public static void Main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 3 , 4 , 5 } ; int n = arr . Length ; findMin ( arr , n ) ; } }
Print all the permutation of length L using the elements of an array | Iterative | C # implementation for above approach ; Convert the number to Lth base and print the sequence ; Sequence is of length L ; Print the ith element of sequence ; Print all the permuataions ; There can be ( len ) ^ l permutations ; Convert i to len th base ; Driver code ; function call
using System ; class GFG { static void convert_To_Len_th_base ( int n , int [ ] arr , int len , int L ) { for ( int i = 0 ; i < L ; i ++ ) { Console . Write ( arr [ n % len ] ) ; n /= len ; } Console . WriteLine ( ) ; } static void print ( int [ ] arr , int len , int L ) { for ( int i = 0 ; i < ( int ) Math . Pow ( len , L ) ; i ++ ) { convert_To_Len_th_base ( i , arr , len , L ) ; } } public static void Main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 3 } ; int len = arr . Length ; int L = 2 ; print ( arr , len , L ) ; } }
Number of possible permutations when absolute difference between number of elements to the right and left are given | C # implementation of the above approach ; Function to find the number of permutations possible of the original array to satisfy the given absolute differences ; To store the count of each a [ i ] in a map ; if n is odd ; check the count of each whether it satisfy the given criteria or not ; there is only 1 way for middle element . ; for others there are 2 ways . ; now find total ways ; When n is even . ; there will be no middle element so for each a [ i ] there will be 2 ways ; Driver Code
using System ; using System . Collections . Generic ; class GFG { static int totalways ( int [ ] arr , int n ) { Dictionary < int , int > cnt = new Dictionary < int , int > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( cnt . ContainsKey ( arr [ i ] ) ) { cnt [ arr [ i ] ] = cnt [ arr [ i ] ] + 1 ; } else { cnt . Add ( arr [ i ] , 1 ) ; } } if ( n % 2 == 1 ) { int start = 0 , endd = n - 1 ; for ( int i = start ; i <= endd ; i = i + 2 ) { if ( i == 0 ) { if ( cnt [ i ] != 1 ) { return 0 ; } } else { if ( cnt [ i ] != 2 ) { return 0 ; } } } int ways = 1 ; start = 2 ; endd = n - 1 ; for ( int i = start ; i <= endd ; i = i + 2 ) { ways = ways * 2 ; } return ways ; } else if ( n % 2 == 0 ) { int start = 1 , endd = n - 1 ; for ( int i = 1 ; i <= endd ; i = i + 2 ) { if ( cnt [ i ] != 2 ) return 0 ; } int ways = 1 ; for ( int i = start ; i <= endd ; i = i + 2 ) { ways = ways * 2 ; } return ways ; } return int . MinValue ; } public static void Main ( String [ ] args ) { int N = 5 ; int [ ] arr = { 2 , 4 , 4 , 0 , 2 } ; Console . WriteLine ( totalways ( arr , N ) ) ; } }
Proizvolov 's Identity | C # program to implement proizvolov 's identity ; Function to implement proizvolov 's identity ; According to proizvolov 's identity ; Driver code ; Function call
using System ; class GFG { static int proizvolov ( int [ ] a , int [ ] b , int n ) { return n * n ; } public static void Main ( ) { int [ ] a = { 1 , 5 , 6 , 8 , 10 } ; int [ ] b = { 9 , 7 , 4 , 3 , 2 } ; int n = a . Length ; Console . WriteLine ( proizvolov ( a , b , n ) ) ; } }
Find the ln ( X ) and log10X with the help of expansion | C # code to Find the ln x and log < sub > 10 < / sub > x with the help of expansion ; Function to calculate ln x using expansion ; terminating value of the loop can be increased to improve the precision ; Function to calculate log10 x ; Driver Code ; setprecision ( 3 ) is used to display the output up to 3 decimal places
using System ; class GFG { static double calculateLnx ( double n ) { double num , mul , cal , sum = 0 ; num = ( n - 1 ) / ( n + 1 ) ; for ( int i = 1 ; i <= 1000 ; i ++ ) { mul = ( 2 * i ) - 1 ; cal = Math . Pow ( num , mul ) ; cal = cal / mul ; sum = sum + cal ; } sum = 2 * sum ; return sum ; } static double calculateLogx ( double lnx ) { return ( lnx / 2.303 ) ; } public static void Main ( String [ ] args ) { double lnx , logx , n = 5 ; lnx = calculateLnx ( n ) ; logx = calculateLogx ( lnx ) ; Console . WriteLine ( " ln ▁ " + n + " ▁ = ▁ " + lnx ) ; Console . WriteLine ( " log10 ▁ " + n + " ▁ = ▁ " + logx ) ; } }
Find the sum of elements of the Matrix generated by the given rules | C # implementation of the approach ; Function to return the required sum ; To store the sum ; For every row ; Update the sum as A appears i number of times in the current row ; Update A for the next row ; Return the sum ; Driver code
using System ; class GFG { static int sum ( int A , int B , int R ) { int sum = 0 ; for ( int i = 1 ; i <= R ; i ++ ) { sum = sum + ( i * A ) ; A = A + B ; } return sum ; } public static void Main ( ) { int A = 5 , B = 3 , R = 3 ; Console . Write ( sum ( A , B , R ) ) ; } }
Count total set bits in all numbers from 1 to n | Set 2 | C # implementation of the approach ; Function to return the sum of the count of set bits in the integers from 1 to n ; Ignore 0 as all the bits are unset ; To store the powers of 2 ; To store the result , it is initialized with n / 2 because the count of set least significant bits in the integers from 1 to n is n / 2 ; Loop for every bit required to represent n ; Total count of pairs of 0 s and 1 s ; totalPairs / 2 gives the complete count of the pairs of 1 s Multiplying it with the current power of 2 will give the count of 1 s in the current bit ; If the count of pairs was odd then add the remaining 1 s which could not be groupped together ; Next power of 2 ; Return the result ; Driver code
using System ; class GFG { static int countSetBits ( int n ) { n ++ ; int powerOf2 = 2 ; int cnt = n / 2 ; while ( powerOf2 <= n ) { int totalPairs = n / powerOf2 ; cnt += ( totalPairs / 2 ) * powerOf2 ; cnt += ( totalPairs % 2 == 1 ) ? ( n % powerOf2 ) : 0 ; powerOf2 <<= 1 ; } return cnt ; } public static void Main ( String [ ] args ) { int n = 14 ; Console . WriteLine ( countSetBits ( n ) ) ; } }
Find the height of a right | C # implementation of the approach ; Function to return the height of the right - angled triangle whose area is X times its base ; Driver code
using System ; class Gfg { static int getHeight ( int X ) { return ( 2 * X ) ; } public static void Main ( ) { int X = 35 ; Console . WriteLine ( getHeight ( X ) ) ; } }
Find sum of inverse of the divisors when sum of divisors and the number is given | C # implementation of above approach ; Function to return the sum of inverse of divisors ; Calculating the answer ; Return the answer ; Driver code ; Function call
using System ; class GFG { static double SumofInverseDivisors ( int N , int Sum ) { double ans = ( double ) ( Sum ) * 1.0 / ( double ) ( N ) ; return ans ; } static public void Main ( ) { int N = 9 ; int Sum = 13 ; Console . Write ( SumofInverseDivisors ( N , Sum ) ) ; } }
Number of triplets such that each value is less than N and each pair sum is a multiple of K | C # implementation of the approach ; Function to return the number of triplets ; Initializing the count array ; Storing the frequency of each modulo class ; If K is odd ; If K is even ; Driver Code ; Function Call
using System ; class GFG { static int NoofTriplets ( int N , int K ) { int [ ] cnt = new int [ K ] ; Array . Fill ( cnt , 0 , cnt . Length , 0 ) ; for ( int i = 1 ; i <= N ; i += 1 ) { cnt [ i % K ] += 1 ; } if ( ( K & 1 ) != 0 ) { return cnt [ 0 ] * cnt [ 0 ] * cnt [ 0 ] ; } else { return ( cnt [ 0 ] * cnt [ 0 ] * cnt [ 0 ] + cnt [ K / 2 ] * cnt [ K / 2 ] * cnt [ K / 2 ] ) ; } } static public void Main ( ) { int N = 3 , K = 2 ; Console . Write ( NoofTriplets ( N , K ) ) ; } }
Find a number containing N | C # implementation of the approach ; Function to compute number using our deduced formula ; Initialize num to n - 1 ; Driver code
using System ; class GFG { static int findNumber ( int n ) { int num = n - 1 ; num = 2 * ( int ) Math . Pow ( 4 , num ) ; num = ( int ) Math . Floor ( num / 3.0 ) ; return num ; } static public void Main ( ) { int n = 5 ; Console . Write ( findNumber ( n ) ) ; } }
Find XOR of numbers from the range [ L , R ] | C # implementation of the approach ; Function to return the XOR of elements from the range [ 1 , n ] ; 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 ; Function to return the XOR of elements from the range [ l , r ] ; Driver code
using System ; class GFG { static int findXOR ( int n ) { int mod = n % 4 ; if ( mod == 0 ) return n ; else if ( mod == 1 ) return 1 ; else if ( mod == 2 ) return n + 1 ; else if ( mod == 3 ) return 0 ; return 0 ; } static int findXOR ( int l , int r ) { return ( findXOR ( l - 1 ) ^ findXOR ( r ) ) ; } public static void Main ( ) { int l = 4 , r = 8 ; Console . WriteLine ( findXOR ( l , r ) ) ; } }
Number of elements from the array which are reachable after performing given operations on D | C # implementation of the approach ; Function to return the GCD of a and b ; Function to return the count of reachable integers from the given array ; GCD of A and B ; To store the count of reachable integers ; If current element can be reached ; Return the count ; 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 findReachable ( int [ ] arr , int D , int A , int B , int n ) { int gcd_AB = GCD ( A , B ) ; int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( ( arr [ i ] - D ) % gcd_AB == 0 ) count ++ ; } return count ; } public static void Main ( ) { int [ ] arr = { 4 , 5 , 6 , 7 , 8 , 9 } ; int n = arr . Length ; int D = 4 , A = 4 , B = 6 ; Console . WriteLine ( findReachable ( arr , D , A , B , n ) ) ; } }
Number of trees whose sum of degrees of all the vertices is L | C # implementation of the approach ; Iterative Function to calculate ( x ^ y ) in O ( log y ) ; Initialize result ; If y is odd , multiply x with result ; y must be even now y = y / 2 ; Function to return the count of required trees ; number of nodes ; Return the result ; Driver code
using System ; class GFG { static long power ( int x , long y ) { long res = 1 ; while ( y > 0 ) { if ( y == 1 ) res = ( res * x ) ; y = y >> 1 ; x = ( x * x ) ; } return res ; } static long solve ( int L ) { int n = L / 2 + 1 ; long ans = power ( n , n - 2 ) ; return ans ; } static public void Main ( ) { int L = 6 ; Console . WriteLine ( solve ( L ) ) ; } }
Change one element in the given array to make it an Arithmetic Progression | C # program to change one element of an array such that the resulting array is in arithmetic progression . ; Finds the initial term and common difference and prints the resulting array . ; Check if the first three elements are in arithmetic progression ; Check if the first element is not in arithmetic progression ; The first and fourth element are in arithmetic progression ; Print the arithmetic progression ; Driver code
using System ; public class AP { static void makeAP ( int [ ] arr , int n ) { int initial_term , common_difference ; if ( n == 3 ) { common_difference = arr [ 2 ] - arr [ 1 ] ; initial_term = arr [ 1 ] - common_difference ; } else if ( ( arr [ 1 ] - arr [ 0 ] ) == arr [ 2 ] - arr [ 1 ] ) { initial_term = arr [ 0 ] ; common_difference = arr [ 1 ] - arr [ 0 ] ; } else if ( ( arr [ 2 ] - arr [ 1 ] ) == ( arr [ 3 ] - arr [ 2 ] ) ) { common_difference = arr [ 2 ] - arr [ 1 ] ; initial_term = arr [ 1 ] - common_difference ; } else { common_difference = ( arr [ 3 ] - arr [ 0 ] ) / 3 ; initial_term = arr [ 0 ] ; } for ( int i = 0 ; i < n ; i ++ ) Console . Write ( initial_term + ( i * common_difference ) + " ▁ " ) ; Console . WriteLine ( ) ; } public static void Main ( String [ ] args ) { int [ ] arr = { 1 , 3 , 7 } ; int n = arr . Length ; makeAP ( arr , n ) ; } }
Find if nCr is divisible by the given prime | C # Implementation of above approach ; Function to return the highest power of p that divides n ! implementing Legendre Formula ; Return the highest power of p which divides n ! ; Function to return N digits number which is divisible by D ; Find the highest powers of p that divide n ! , r ! and ( n - r ) ! ; If nCr is divisible by p ; Driver code
using System ; class GFG { static int getfactor ( int n , int p ) { int pw = 0 ; while ( n != 0 ) { n /= p ; pw += n ; } return pw ; } static int isDivisible ( int n , int r , int p ) { int x1 = getfactor ( n , p ) ; int x2 = getfactor ( r , p ) ; int x3 = getfactor ( n - r , p ) ; if ( x1 > x2 + x3 ) return 1 ; return 0 ; } static public void Main ( ) { int n = 7 , r = 2 , p = 7 ; if ( isDivisible ( n , r , p ) == 1 ) Console . WriteLine ( " Yes " ) ; else Console . WriteLine ( " No " ) ; } }
Check if the number is even or odd whose digits and base ( radix ) is given | C # implementation of the approach ; Function that returns true if the number represented by arr [ ] is even in base r ; If the base is even , then the last digit is checked ; If base is odd , then the number of odd digits are checked ; To store the count of odd digits ; Number is odd ; Driver code
using System ; class GFG { static bool isEven ( int [ ] arr , int n , int r ) { if ( r % 2 == 0 ) { if ( arr [ n - 1 ] % 2 == 0 ) return true ; } else { int oddCount = 0 ; for ( int i = 0 ; i < n ; ++ i ) { if ( arr [ i ] % 2 != 0 ) oddCount ++ ; } if ( oddCount % 2 == 0 ) return true ; } return false ; } public static void Main ( ) { int [ ] arr = { 1 , 0 } ; int n = arr . Length ; int r = 2 ; if ( isEven ( arr , n , r ) ) Console . WriteLine ( " Even " ) ; else Console . WriteLine ( " Odd " ) ; } }
Bitwise AND of sub | C # implementation of the approach ; Function to return the minimum possible value of | K - X | where X is the bitwise AND of the elements of some sub - array ; Check all possible sub - arrays ; Find the overall minimum ; No need to perform more AND operations as | k - X | will increase ; Driver code
using System ; class GFG { static int closetAND ( int [ ] arr , int n , int k ) { int ans = int . MaxValue ; for ( int i = 0 ; i < n ; i ++ ) { int X = arr [ i ] ; for ( int j = i ; j < n ; j ++ ) { X &= arr [ j ] ; ans = Math . Min ( ans , Math . Abs ( k - X ) ) ; if ( X <= k ) break ; } } return ans ; } public static void Main ( String [ ] args ) { int [ ] arr = { 4 , 7 , 10 } ; int n = arr . Length ; int k = 2 ; Console . WriteLine ( closetAND ( arr , n , k ) ) ; } }
Count of quadruplets from range [ L , R ] having GCD equal to K | C # implementation of the approach ; Function to return the gcd of a and b ; Function to return the count of quadruplets having gcd = k ; Count the frequency of every possible gcd value in the range ; To store the required count ; Calculate the answer using frequency values ; Return the required count ; 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 countQuadruplets ( int l , int r , int k ) { int [ ] frequency = new int [ r + 1 ] ; for ( int i = l ; i <= r ; i ++ ) { for ( int j = l ; j <= r ; j ++ ) { frequency [ gcd ( i , j ) ] ++ ; } } long answer = 0 ; for ( int i = 1 ; i <= r ; i ++ ) { for ( int j = 1 ; j <= r ; j ++ ) { if ( gcd ( i , j ) == k ) { answer += ( frequency [ i ] * frequency [ j ] ) ; } } } return ( int ) answer ; } static public void Main ( ) { int l = 1 , r = 10 , k = 2 ; Console . WriteLine ( countQuadruplets ( l , r , k ) ) ; } }
Rearrange the array to maximize the number of primes in prefix sum of the array | C # implementation of the approach ; Function to print the re - arranged array ; Count the number of ones and twos in a [ ] ; If the array element is 1 ; Array element is 2 ; If it has at least one 2 Fill up first 2 ; Decrease the cnt of ones if even ; Fill up with odd count of ones ; Fill up with remaining twos ; If even ones , then fill last position ; Print the rearranged array ; Driver code
using System ; class GFG { static void solve ( int [ ] a , int n ) { int ones = 0 , twos = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] == 1 ) ones ++ ; else twos ++ ; } int ind = 0 ; if ( twos > 0 ) a [ ind ++ ] = 2 ; bool evenOnes = ( ones % 2 == 0 ) ? true : false ; if ( evenOnes ) ones -= 1 ; for ( int i = 0 ; i < ones ; i ++ ) a [ ind ++ ] = 1 ; for ( int i = 0 ; i < twos - 1 ; i ++ ) a [ ind ++ ] = 2 ; if ( evenOnes ) a [ ind ++ ] = 1 ; for ( int i = 0 ; i < n ; i ++ ) Console . Write ( a [ i ] + " ▁ " ) ; } static public void Main ( ) { int [ ] a = { 1 , 2 , 1 , 2 , 1 } ; int n = a . Length ; solve ( a , n ) ; } }
Generate an Array in which count of even and odd sum sub | C # implementation of the approach ; Function to generate and print the required array ; Find the number of odd prefix sums ; If no odd prefix sum found ; Calculating the number of even prefix sums ; Stores the current prefix sum ; If current prefix sum is even ; Print 0 until e = EvenPreSums - 1 ; Print 1 when e = EvenPreSums ; Print 0 for rest of the values ; Driver code
using System ; class GFG { static void CreateArray ( int N , int even , int odd ) { int EvenPreSums = 1 ; int temp = - 1 ; int OddPreSums = 0 ; for ( int i = 0 ; i <= N + 1 ; i ++ ) { if ( i * ( ( N + 1 ) - i ) == odd ) { temp = 0 ; OddPreSums = i ; break ; } } if ( temp == - 1 ) { Console . WriteLine ( temp ) ; } else { EvenPreSums = ( ( N + 1 ) - OddPreSums ) ; int e = 1 ; int o = 0 ; int CurrSum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( CurrSum % 2 == 0 ) { if ( e < EvenPreSums ) { e ++ ; Console . Write ( "0 ▁ " ) ; } else { o ++ ; Console . Write ( "1 ▁ " ) ; CurrSum ++ ; } } else { if ( e < EvenPreSums ) { e ++ ; Console . Write ( "1 ▁ " ) ; CurrSum ++ ; } else { o ++ ; Console . Write ( "0 ▁ " ) ; } } } Console . WriteLine ( ) ; } } static public void Main ( ) { int N = 15 ; int even = 60 , odd = 60 ; CreateArray ( N , even , odd ) ; } }
Minimum operations required to change the array such that | arr [ i ] | C # implementation of the approach ; Function to return the minimum number of operations required ; Minimum and maximum elements from the array ; To store the minimum number of operations required ; To store the number of operations required to change every element to either ( num - 1 ) , num or ( num + 1 ) ; If current element is not already num ; Add the count of operations required to change arr [ i ] ; Update the minimum operations so far ; Driver code
using System ; using System . Linq ; class GFG { static int changeTheArray ( int [ ] arr , int n ) { int minEle = arr . Min ( ) ; int maxEle = arr . Max ( ) ; int minOperations = int . MaxValue ; for ( int num = minEle ; num <= maxEle ; num ++ ) { int operations = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] != num ) { operations += ( Math . Abs ( num - arr [ i ] ) - 1 ) ; } } minOperations = Math . Min ( minOperations , operations ) ; } return minOperations ; } public static void Main ( String [ ] args ) { int [ ] arr = { 10 , 1 , 4 } ; int n = arr . Length ; Console . WriteLine ( changeTheArray ( arr , n ) ) ; } }
Choose X such that ( A xor X ) + ( B xor X ) is minimized | C # implementation of the approach ; Function to return the integer X such that ( A xor X ) + ( B ^ X ) is minimized ; While either A or B is non - zero ; Position at which both A and B have a set bit ; Inserting a set bit in x ; Right shifting both numbers to traverse all the bits ; Driver code
using System ; class GFG { static int findX ( int A , int B ) { int j = 0 , x = 0 ; while ( A != 0 B != 0 ) { if ( ( A % 2 == 1 ) && ( B % 2 == 1 ) ) { x += ( 1 << j ) ; } A >>= 1 ; B >>= 1 ; j += 1 ; } return x ; } public static void Main ( String [ ] args ) { int A = 2 , B = 3 ; int X = findX ( A , B ) ; Console . WriteLine ( " X ▁ = ▁ " + X + " , ▁ Sum ▁ = ▁ " + ( ( A ^ X ) + ( B ^ X ) ) ) ; } }
Choose X such that ( A xor X ) + ( B xor X ) is minimized | C # implementation of above approach ; Finding X ; Finding Sum ; Driver Code
using System ; class GFG { public static int findX ( int A , int B ) { return A & B ; } public static int findSum ( int A , int B ) { return A ^ B ; } public static void Main ( String [ ] args ) { int A = 2 , B = 3 ; Console . Write ( " X ▁ = ▁ " + findX ( A , B ) + " , ▁ Sum ▁ = ▁ " + findSum ( A , B ) ) ; } }
Compare sum of first N | C # implementation of the approach ; Function that returns true if sum of first n - 1 elements of the array is equal to the last element ; Find the sum of first n - 1 elements of the array ; If sum equals to the last element ; Driver code
using System ; class GFG { static bool isSumEqual ( int [ ] ar , int n ) { int sum = 0 ; for ( int i = 0 ; i < n - 1 ; i ++ ) sum += ar [ i ] ; if ( sum == ar [ n - 1 ] ) return true ; return false ; } static public void Main ( ) { int [ ] arr = { 1 , 2 , 3 , 4 , 10 } ; int n = arr . Length ; if ( isSumEqual ( arr , n ) ) Console . WriteLine ( " Yes " ) ; else Console . WriteLine ( " No " ) ; } }
Count number of 1 s in the array after N moves | C # implementation of the above approach ; Function to count number of perfect squares ; Counting number of perfect squares between a and b ; Function to count number of 1 s in array after N moves ; Driver Code ; Initialize array size ; Initialize all elements to 0
using System ; class GFG { static double perfectSquares ( int a , int b ) { return ( Math . Floor ( Math . Sqrt ( b ) ) - Math . Ceiling ( Math . Sqrt ( a ) ) + 1 ) ; } static double countOnes ( int [ ] arr , int n ) { return perfectSquares ( 1 , n ) ; } static public void Main ( ) { int N = 10 ; int [ ] arr = { 0 } ; Console . WriteLine ( countOnes ( arr , N ) ) ; } }
Find the position of box which occupies the given ball | C # implementation of the approach ; Function to print the position of each boxes where a ball has to be placed ; Find the cumulative sum of array A [ ] ; Find the position of box for each ball ; Row number ; Column ( position of box in particular row ) ; Row + 1 denotes row if indexing of array start from 1 ; Driver code
using System ; class GFG { static void printPosition ( int [ ] A , int [ ] B , int sizeOfA , int sizeOfB ) { for ( int i = 1 ; i < sizeOfA ; i ++ ) { A [ i ] += A [ i - 1 ] ; } for ( int i = 0 ; i < sizeOfB ; i ++ ) { int row = lower_bound ( A , 0 , A . Length , B [ i ] ) ; int boxNumber = ( row >= 1 ) ? B [ i ] - A [ row - 1 ] : B [ i ] ; Console . WriteLine ( row + 1 + " , ▁ " + boxNumber + " STRNEWLINE " ) ; } } private static int lower_bound ( int [ ] a , int low , int high , int element ) { while ( low < high ) { int middle = low + ( high - low ) / 2 ; if ( element > a [ middle ] ) { low = middle + 1 ; } else { high = middle ; } } return low ; } static public void Main ( ) { int [ ] A = { 2 , 2 , 2 , 2 } ; int [ ] B = { 1 , 2 , 3 , 4 } ; int sizeOfA = A . Length ; int sizeOfB = B . Length ; printPosition ( A , B , sizeOfA , sizeOfB ) ; } }
Highest power of a number that divides other number | C # program to implement the above approach ; Function to get the prime factors and its count of times it divides ; Count the number of 2 s that divide n ; n must be odd at this point . So we can skip one element ( Note i = i + 2 ) ; While i divides n , count i and divide n ; This condition is to handle the case when n is a prime number greater than 2 ; Function to return the highest power ; Initialize two arrays ; Get the prime factors of n and m ; Iterate and find the maximum power ; If i not a prime factor of n and m ; If i is a prime factor of n and m If count of i dividing m is more than i dividing n , then power will be 0 ; If i is a prime factor of M ; get the maximum power ; Drivers code
using System ; class GFG { static void primeFactors ( int n , int [ ] freq ) { int cnt = 0 ; while ( n % 2 == 0 ) { cnt ++ ; n = n / 2 ; } freq [ 2 ] = cnt ; for ( int i = 3 ; i <= Math . Sqrt ( n ) ; i = i + 2 ) { cnt = 0 ; while ( n % i == 0 ) { cnt ++ ; n = n / i ; } freq [ i ] = cnt ; } if ( n > 2 ) freq [ n ] = 1 ; } static int getMaximumPower ( int n , int m ) { int [ ] freq1 = new int [ n + 1 ] ; int [ ] freq2 = new int [ m + 1 ] ; primeFactors ( n , freq1 ) ; primeFactors ( m , freq2 ) ; int maxi = 0 ; for ( int i = 2 ; i <= m ; i ++ ) { if ( freq1 [ i ] == 0 && freq2 [ i ] == 0 ) continue ; if ( freq2 [ i ] > freq1 [ i ] ) return 0 ; if ( freq2 [ i ] != 0 ) { maxi = Math . Max ( maxi , freq1 [ i ] / freq2 [ i ] ) ; } } return maxi ; } public static void Main ( String [ ] args ) { int n = 48 , m = 4 ; Console . WriteLine ( getMaximumPower ( n , m ) ) ; } }
Find the number of divisors of all numbers in the range [ 1 , n ] | C # implementation of the approach ; Function to find the number of divisors of all numbers in the range [ 1 , n ] ; Array to store the count of divisors ; For every number from 1 to n ; Increase divisors count for every number divisible by i ; Print the divisors ; Driver code
using System ; class GFG { static void findDivisors ( int n ) { int [ ] div = new int [ n + 1 ] ; for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 1 ; j * i <= n ; j ++ ) div [ i * j ] ++ ; } for ( int i = 1 ; i <= n ; i ++ ) Console . Write ( div [ i ] + " ▁ " ) ; } static void Main ( ) { int n = 10 ; findDivisors ( n ) ; } }
Predict the winner of the game on the basis of absolute difference of sum by selecting numbers | C # implementation of the approach ; Function to decide the winner ; Iterate for all numbers in the array ; If mod gives 0 ; If mod gives 1 ; If mod gives 2 ; If mod gives 3 ; Check the winning condition for X ; Driver code
using System ; class GFG { static int decideWinner ( int [ ] a , int n ) { int count0 = 0 ; int count1 = 0 ; int count2 = 0 ; int count3 = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] % 4 == 0 ) count0 ++ ; else if ( a [ i ] % 4 == 1 ) count1 ++ ; else if ( a [ i ] % 4 == 2 ) count2 ++ ; else if ( a [ i ] % 4 == 3 ) count3 ++ ; } if ( count0 % 2 == 0 && count1 % 2 == 0 && count2 % 2 == 0 && count3 == 0 ) return 1 ; else return 2 ; } public static void Main ( ) { int [ ] a = { 4 , 8 , 5 , 9 } ; int n = a . Length ; if ( decideWinner ( a , n ) == 1 ) Console . Write ( " X ▁ wins " ) ; else Console . Write ( " Y ▁ wins " ) ; } }
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 ; Instead of converting all prefixes to decimal , take reminder with x ; If number is divisible by x then reminder = 0 ; Driver code
using System ; class GFG { public 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 ] ) % x ; if ( number == 0 ) count += 1 ; } return count ; } public static void Main ( ) { int [ ] arr = { 1 , 0 , 1 , 0 , 1 , 1 , 0 } ; int n = 7 ; int x = 2 ; Console . Write ( CntDivbyX ( arr , n , x ) ) ; } }
Length of the smallest number which is divisible by K and formed by using 1 's only | C # implementation of the approach ; Function to return length of the resultant number ; If K is a multiple of 2 or 5 ; Instead of generating all possible numbers 1 , 11 , 111 , 111 , ... , K 1 's Take remainder with K ; If number is divisible by k then remainder will be 0 ; Driver code
using System ; class GFG { public static int numLen ( int K ) { if ( K % 2 == 0 K % 5 == 0 ) return - 1 ; int number = 0 ; int len = 1 ; for ( len = 1 ; len <= K ; len ++ ) { number = ( number * 10 + 1 ) % K ; if ( number == 0 ) return len ; } return - 1 ; } public static void Main ( ) { int K = 7 ; Console . WriteLine ( numLen ( K ) ) ; } }
Sum of multiplication of triplet of divisors of a number | C # implementation of the approach ; Global array declaration ; Function to find the sum of multiplication of every triplet in the divisors of a number ; sum1 [ x ] represents the sum of all the divisors of x ; Adding i to sum1 [ j ] because i is a divisor of j ; sum2 [ x ] represents the sum of all the divisors of x ; Here i is divisor of j and sum1 [ j ] - i represents sum of all divisors of j which do not include i so we add i * ( sum1 [ j ] - i ) to sum2 [ j ] ; In the above implementation we have considered every pair two times so we have to divide every sum2 array element by 2 ; Here i is the divisor of j and we are trying to add the sum of multiplication of all triplets of divisors of j such that one of the divisors is i ; In the above implementation we have considered every triplet three times so we have to divide every sum3 array element by 3 ; Print the results ; Driver code ; Precomputing
using System ; class GFG { static int max_Element = ( int ) ( 1e6 + 5 ) ; static int [ ] sum1 = new int [ max_Element ] ; static int [ ] sum2 = new int [ max_Element ] ; static int [ ] sum3 = new int [ max_Element ] ; static void precomputation ( int [ ] arr , int n ) { for ( int i = 1 ; i < max_Element ; i ++ ) for ( int j = i ; j < max_Element ; j += i ) sum1 [ j ] += i ; for ( int i = 1 ; i < max_Element ; i ++ ) for ( int j = i ; j < max_Element ; j += i ) sum2 [ j ] += ( sum1 [ j ] - i ) * i ; for ( int i = 1 ; i < max_Element ; i ++ ) sum2 [ i ] /= 2 ; for ( int i = 1 ; i < max_Element ; i ++ ) for ( int j = i ; j < max_Element ; j += i ) sum3 [ j ] += i * ( sum2 [ j ] - i * ( sum1 [ j ] - i ) ) ; for ( int i = 1 ; i < max_Element ; i ++ ) sum3 [ i ] /= 3 ; for ( int i = 0 ; i < n ; i ++ ) Console . Write ( sum3 [ arr [ i ] ] + " ▁ " ) ; } public static void Main ( ) { int [ ] arr = { 9 , 5 , 6 } ; int n = arr . Length ; precomputation ( arr , n ) ; } }
Sum of Fibonacci Numbers in a range | C # implementation of the approach ; Function to return the nth Fibonacci number ; Function to return the required sum ; Using our deduced result ; 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 = fib ( r + 2 ) - fib ( l + 1 ) ; return sum ; } public static void Main ( ) { int l = 4 , r = 8 ; Console . WriteLine ( calculateSum ( l , r ) ) ; } }
Print the balanced bracket expression using given brackets | C # implementation of the approach ; Function to print balanced bracket expression if it is possible ; If the condition is met ; Print brackets of type - 1 ; Print brackets of type - 3 ; Print brackets of type - 4 ; Print brackets of type - 2 ; If the condition is not met ; Driver code
using System ; class GFG { static void printBalancedExpression ( int a , int b , int c , int d ) { if ( ( ( a == d ) && ( a != 0 ) ) || ( ( a == 0 ) && ( c == 0 ) && ( d == 0 ) ) ) { for ( int i = 1 ; i <= a ; i ++ ) Console . Write ( " ( ( " ) ; for ( int i = 1 ; i <= c ; i ++ ) Console . Write ( " ) ( " ) ; for ( int i = 1 ; i <= d ; i ++ ) Console . Write ( " ) ) " ) ; for ( int i = 1 ; i <= b ; i ++ ) Console . Write ( " ( ) " ) ; } else Console . Write ( - 1 ) ; } public static void Main ( ) { int a = 3 , b = 1 , c = 4 , d = 3 ; printBalancedExpression ( a , b , c , d ) ; } }