News Leaflets
A leading news portal.

Find set of size K such that any value of the set is co-prime with any Array element

0 18

  

import java.io.*;

import java.util.*;

  

public class GFG {

  

    

    public static void findSet(int n, int k)

    {

        int dp[] = new int[n + 1];

        for (int i = 1; i <= n; i++) {

            dp[i] = -1;

        }

  

        

        dp[1] = 0;

        int together = 0;

        int single = 1;

        for (int i = 2; i <= n; i++) {

            if (i % 2 == 0 && dp[i] == -1) {

                dp[i] = 1;

                together++;

            }

            else if (dp[i] == -1) {

                int z = 2 * i;

                int flag = -1;

                while (z <= n) {

                    flag = 1;

                    if (dp[z] == -1) {

                        together++;

                    }

                    dp[z] = 1;

                    z += i;

                }

                if (flag == 1) {

                    dp[i] = 1;

                    together++;

                }

                else {

                    dp[i] = 0;

                    single++;

                }

            }

        }

        if (k <= single) {

            for (int i = 1; i <= n; i++) {

                if (k != 0 && dp[i] == 0) {

                    System.out.print(i + " ");

                    k--;

                }

            }

        }

        else if (k >= together) {

  

            k -= together;

            for (int i = 1; i <= n; i++) {

                if (k != 0 && dp[i] == 0) {

                    System.out.print(i + " ");

                    k--;

                }

                else if (dp[i] == 1) {

                    System.out.print(i + " ");

                }

            }

        }

        else {

            System.out.println(-1);

        }

    }

  

    

    public static void main(String[] args)

    {

        int N = 4;

        int K = 1;

  

        

        findSet(N, K);

    }

}

FOLLOW US ON GOOGLE NEWS

Read original article here

Denial of responsibility! News Leaflets is an automatic aggregator of the all world’s media. In each content, the hyperlink to the primary source is specified. All trademarks belong to their rightful owners, all materials to their authors. If you are the owner of the content and do not want us to publish your materials, please contact us by email – [email protected]. The content will be deleted within 24 hours.

Leave a comment