Home > Software design >  Why is this code not printing the prime factors of num?
Why is this code not printing the prime factors of num?

Time:07-15

I wrote this code for obtaining the prime factors of a number taken as an input from the user.

#include<bits/stdc  .h>
using namespace std;

void prime_Factors(int);
bool isPrime(int);

int main()
{
    int num;
    cout << "Enter the number to find it's prime factors: ";
    cin >> num;
    prime_Factors(num);
}

void prime_Factors(int n1)
{
    for(int i = 2; i<n1; i  )
    {
        if(isPrime(i))
        {
            int x = i;
            while(n1%x==0)
            {
                cout << i << " ";
                x *= i; 
            } 
        }
    }
}

bool isPrime(int n0)
{
    if(n0==1)
        return false;
    for(int i = 0; i*i <= n0; i  )
    {
         if(n0%i==0)
            return false;
    }
    return true;
}

The prime_Factors() function call in main() function is not printing the prime factors. Pls help!!

CodePudding user response:

The ranges of the loops are wrong.

Firstly, the loop for(int i = 2; i<n1; i ) will fail to find prime factors of prime numbers (the numbers theirself). It should be for(int i = 2; i<=n1; i ).

Secondly, the loop for(int i = 0; i*i <= n0; i ) will result in division-by-zero. It should be for(int i = 2; i*i <= n0; i ).

CodePudding user response:

Thinking about using the Sieve of Eratosthenes made me try it out:

#include <iostream>
#include <cstdint>
#include <vector>

void prime_factors(uint32_t n) {
    while(n % 2 == 0) {
        std::cout << "2 ";
        n /= 2;
    }
    std::vector<bool> sieve(n / 2, true);
    for (uint32_t i = 3; i * i <= n; i  = 2) {
        if (sieve.at(i / 2 - 1)) {
            uint32_t j = i * i;
            for (; j < n; j  = 2 * i) {
                sieve.at(j / 2 - 1) = false;
            }
            if (j == n) {
                do {
                    std::cout << i << " ";
                    n /= i;
                } while (!sieve.at(n / 2 - 1));
            }
        }
    }
    if (n > 1) std::cout << n;
    std::cout << "\n";
}

int main() {
    prime_factors(123456789);
}

https://godbolt.org/z/8doWbYrs6

  • Related