Distinct Prime Factors of an Array | C # implementation of the above approach ; Function to return an array of prime numbers upto n using Sieve of Eratosthenes ; Function to return distinct prime factors from the given array ; Creating an empty array to store distinct prime factors ; Iterating through all the prime numbers and check if any of the prime numbers is a factor of the given input array ; Driver code ; Finding prime numbers upto 10000 using Sieve of Eratosthenes
using System ; using System . Collections . Generic ; class GFG { static List < int > sieve ( int n ) { List < int > prime = new List < int > ( ) ; for ( int i = 0 ; i < n + 1 ; i ++ ) prime . Add ( 0 ) ; int p = 2 ; while ( p * p <= n ) { if ( prime [ p ] == 0 ) { for ( int i = 2 * p ; i < n + 1 ; i += p ) prime [ i ] = 1 ; } p += 1 ; } List < int > allPrimes = new List < int > ( ) ; for ( int i = 2 ; i < n ; i ++ ) { if ( prime [ i ] == 0 ) allPrimes . Add ( i ) ; } return allPrimes ; } static List < int > distPrime ( List < int > arr , List < int > allPrimes ) { List < int > list1 = new List < int > ( ) ; for ( int i = 0 ; i < allPrimes . Count ; i ++ ) { for ( int j = 0 ; j < arr . Count ; j ++ ) { if ( arr [ j ] % allPrimes [ i ] == 0 ) { list1 . Add ( allPrimes [ i ] ) ; break ; } } } return list1 ; } public static void Main ( string [ ] args ) { List < int > allPrimes = new List < int > ( sieve ( 10000 ) ) ; List < int > arr = new List < int > ( ) ; arr . Add ( 15 ) ; arr . Add ( 30 ) ; arr . Add ( 60 ) ; List < int > ans = new List < int > ( distPrime ( arr , allPrimes ) ) ; Console . Write ( " [ " ) ; for ( int i = 0 ; i < ans . Count ; i ++ ) Console . Write ( ans [ i ] + " ▁ " ) ; Console . Write ( " ] " ) ; } }