Question #124959

Write a program to enter a number, pass its reference to a function, store this reference into a pointer variable, and then calculate & display prime factors by using do-while loop through pointer variable in which reference was stored.

Expert's answer

#include <iostream>
#include <cmath>

using namespace std;

// A function to print all prime factors of n
void primeFactors(int *n){
    while ((*n) % 2 == 0)
    {
        cout << 2 << " ";
        (*n) /= 2;
    }
    double x = sqrt(*n);
    for (int i = 3; i <= x; i += 2){
        while ((*n) % i == 0){
            cout << i << " ";
            (*n) /= i;
        }
    }
    if((*n) != 1)
        cout << (*n);
}

int main(){
    int n;
    int *p;// Pointer variable
    cout << "Enter number: ";  cin >> n;

    p = &n;// reference into a pointer variable,

    cout << "Prime factors: " << endl;
    primeFactors(p);
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

LATEST TUTORIALS
APPROVED BY CLIENTS