Thursday, May 19, 2022
HomeSoftware DevelopmentDistinct Prime Elements of a given quantity N

Distinct Prime Elements of a given quantity N


Given a quantity N, the duty is to search out the distinct Prime Elements of N.

Examples:

Enter: N = 12
Output: 2 3
Clarification: The elements of 12 are 1, 2, 3, 4, 6, 12.
Amongst these the distinct prime elements are 2 and three.

Enter: N = 39
Output: 3 13

 

Strategy: The method is to make use of a map to verify whether or not a given issue of the quantity has occurred earlier or not. Now comply with the beneath steps to resolve this drawback:

  1. Create a map visited to maintain monitor of all earlier prime elements.
  2. Create a variable C, and initialise it with 2.
  3. Whereas N is divisible by C, print C if C will not be current within the map. Now divide N by C. Additionally increment C by 1.

Under is the implementation of the above method:

C++

#embrace <bits/stdc++.h>

utilizing namespace std;

 

void distinctPrimeFactors(int N)

{

    if (N < 2) {

        cout << -1;

    }

 

    int c = 2;

    unordered_map<int, bool> visited;

 

    whereas (N > 1) {

        if (N % c == 0) {

            if (!visited) {

                cout << c << " ";

                visited = 1;

            }

            N /= c;

        }

        else

            c++;

    }

}

 

int most important()

{

    int N = 39;

    distinctPrimeFactors(N);

    return 0;

}

Javascript

<script>

    

 

    

    

    const distinctPrimeFactors = (N) => {

        if (N < 2) {

            doc.write(-1);

        }

 

        let c = 2;

        let visited = {};

 

        whereas (N > 1) {

            if (N % c == 0) {

                if (!(c in visited)) {

                    doc.write(`${c} `);

                    visited = 1;

                }

                N = parseInt(N / c);

            }

            else

                c++;

        }

    }

 

    

 

    let N = 39;

    distinctPrimeFactors(N);

 

 

</script>

 
 

 

Time Complexity: O(N)
Auxiliary Area: O(N1/2)

 

Consideration reader! Don’t cease studying now. Pay money for all of the essential mathematical ideas for aggressive programming with the Important Maths for CP Course at a student-friendly value. To finish your preparation from studying a language to DS Algo and lots of extra,  please refer Full Interview Preparation Course.

RELATED ARTICLES

Most Popular

Recent Comments