Search
 
SCRIPT & CODE EXAMPLE
 

CPP

prime factorisation of a number in c++

// Function that returns a vector containing all the prime factors of n (25 --> 5, 5)
vector<long long> prime_factorisation(long long n)
{
    //spf is smallest prime factor
    map<long long, long long> spf;
    vector<long long> ans(0);
    for(long long i = 2; i <= n; i++) spf[i] = i;

    for (long long i = 2; i <= n; i++)
        if (spf[i] == i)
            for (long long j = i * i; j <= n; j += i)
                if (spf[j] == j)
                    spf[j] = i;

    while (n != 1)
    {
        ans.push_back(spf[n]);
        n /= spf[n];
    }
    return ans;
}
Comment

how to factorize a number in c++

// C++ program to print all prime factors
#include <bits/stdc++.h>
using namespace std;
 
// A function to print all prime
// factors of a given number n
void primeFactors(int n)
{
    // Print the number of 2s that divide n
    while (n % 2 == 0)
    {
        cout << 2 << " ";
        n = n/2;
    }
 
    // n must be odd at this point. So we can skip
    // one element (Note i = i +2)
    for (int i = 3; i <= sqrt(n); i = i + 2)
    {
        // While i divides n, print i and divide n
        while (n % i == 0)
        {
            cout << i << " ";
            n = n/i;
        }
    }
 
    // This condition is to handle the case when n
    // is a prime number greater than 2
    if (n > 2)
        cout << n << " ";
}
 
/* Driver code */
int main()
{
    int n = 315;
    primeFactors(n);
    return 0;
}
 
// This is code is contributed by rathbhupendra
Comment

PREVIOUS NEXT
Code Example
Cpp :: header file for unordered_map in c++ 
Cpp :: initialize 2d vector 
Cpp :: why are inline keyword in header c++ 
Cpp :: c++ first letter of string 
Cpp :: convert string toupper and tolower in cpp 
Cpp :: clear the input buffer in cpp 
Cpp :: how to add an element to std::map 
Cpp :: log base 10 c++ 
Cpp :: c++ template function 
Cpp :: comparator for priority queue c++ 
Cpp :: c++ how to read from a file 
Cpp :: what is c++ used for 
Cpp :: c++ remove text file 
Cpp :: indexing strings in c++ 
Cpp :: cpp pushfront vector 
Cpp :: how to reverse a vector 
Cpp :: c++ print binary treenode 
Cpp :: find second highest number in c++ 
Cpp :: untitled goose game 
Cpp :: inline in class in C++ 
Cpp :: how to add external library in clion 
Cpp :: c++ int length 
Cpp :: c++ check substring 
Cpp :: Convert a hexadecimal number into decimal c++ 
Cpp :: C++ Conditions and If Statements 
Cpp :: how to know the number of a certain substring in a string in c++ 
Cpp :: comparing characters of a string in c++ 
Cpp :: array of struct in c++ 
Cpp :: explicit c++ 
Cpp :: what do you mean by smallest anagram of a string 
ADD CONTENT
Topic
Content
Source link
Name
4+4 =