Answer to Question #124959 in C++ for asad ullah khan

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.
1
Expert's answer
2020-07-03T09:46:17-0400
#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!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS