Search
 
SCRIPT & CODE EXAMPLE
 

CPP

c++ Least prime factor of numbers till n

// C++ program to print the least prime factors
// of numbers less than or equal to
// n using modified Sieve of Eratosthenes
#include<bits/stdc++.h>
using namespace std;
 
void leastPrimeFactor(int n)
{
    // Create a vector to store least primes.
    // Initialize all entries as 0.
    vector<int> least_prime(n+1, 0);
 
    // We need to print 1 for 1.
    least_prime[1] = 1;
 
    for (int i = 2; i <= n; i++)
    {
        // least_prime[i] == 0
        // means it i is prime
        if (least_prime[i] == 0)
        {
            // marking the prime number
            // as its own lpf
            least_prime[i] = i;
 
            // mark it as a divisor for all its
            // multiples if not already marked
            for (int j = i*i; j <= n; j += i)
                if (least_prime[j] == 0)
                   least_prime[j] = i;
        }
    }
 
    // print least prime factor of
    // of numbers till n
    for (int i = 1; i <= n; i++)
        cout << "Least Prime factor of "
             << i << ": " << least_prime[i] << "
";
}
 
// Driver program to test above function
int main()
{
    int n = 10;
    leastPrimeFactor(n);
    return 0;
}
Comment

PREVIOUS NEXT
Code Example
Cpp :: joining two vectors in c++ 
Cpp :: linked list in c++ 
Cpp :: c++ finding gcd 
Cpp :: c++ #include 
Cpp :: ++ how to write quotation mark in a string 
Cpp :: cpp auto 
Cpp :: Function to calculate compound interest in C++ 
Cpp :: c++ get pointer from unique_ptr 
Cpp :: set size in c++ 
Cpp :: c++ average vector 
Cpp :: Nested if...else 
Cpp :: polymorphism in c++ 
Cpp :: tuple vector c++ 
Cpp :: do while c++ 
Cpp :: how to sort array in c++ stockoverflow 
Cpp :: prevent getting data from data-tooltip-content tippyjs 
Cpp :: fill two dimensional array c++ 
Cpp :: use of strstr in c++ 
Cpp :: c++ variable type 
Cpp :: cmd color text c++ 
Cpp :: Operators in C / C++ 
Cpp :: variadic template in c++ 
Cpp :: c++ linked list delete node 
Cpp :: hide window c++ 
Cpp :: copy assignment operator in c++ 
Cpp :: find factorial in c++ using class 
Cpp :: c language all keywords in string 
Cpp :: c++ pointers 
Cpp :: c++ custom printf 
Cpp :: set to vector c++ 
ADD CONTENT
Topic
Content
Source link
Name
4+8 =