I am relatively new in C++ and I have been doing a self-study using the "C++ Without Fear" E-book by Brian Overland and some other online resources.
I am however finding it difficult completing an Exercise. The program is supposed to get all prime factors of a number by:
Writing two functions: get_all_divisors and get_lowest_divisor. The main function should call get_all_divisors, which in turn has a loop: get_all_divisors calls get_lowest_divisor repeatedly, each time replacing n with n/i, where i is the divisor that was found. If n itself is returned, then the number is prime, and the loop should stop.)
#include <iostream>
#include <cmath>
usingnamespace std;
void get_all_divisors(int n);
void get_lowest_divisor(int num);
int main()
{
int n = 0;
cout << "Enter a number and press ENTER: ";
cin >> n;
get_all_divisors(n);
cout << endl;
//system("PAUSE");
return 0;
}
void get_all_divisors(int n)
{
double sqrt_of_n = sqrt(n);
for (int i = 2; i <= sqrt_of_n; ++i)
{
while (n % i == 0)
{ // If i divides n evenly,
n/=i;
cout << i << ", "; // Print i,
//get_divisors(n / i); // Factor n/i,
return; // and exit.
}
}
}
void get_lowest_divisor(int num)
{
for (int i = 2; i <= sqrt(num); ++i)
{
while (num % i == 0)
{ // If i divides n evenly,
num/=i;
}
}
}
I will be glad if someone can assist me with a way to do this.
PS: I strictly want to implement this using 2 functions where the main calls one which in turn calls the other. Thank you.
first, change the prototype of the funciton, you need to return a number to the caller int get_lowest_divisor(int num);
for get_all_divisors() as you need to return a sequence you may use std::vector
if you don't know about it, fine, just print to screen.
> get_all_divisors calls get_lowest_divisor repeatedly, each time replacing n
> with n/i, where i is the divisor that was found. If n itself is returned,
> then the number is prime, and the loop should stop.)
¿did you copy that from the assignment?
because what you've coded is quite different from that
write the pseudocode of get_all_divisors(), assume that there is a get_lowest_divisor() function that works perfectly
prime factorization has to account for multiples of the same value.
for example the PF of 8 is 2,2,2
I think you may need to have a condition that if you found a factor, check to see if it is a factor of num/i again until it no longer is a factor, otherwise you might get 4 as a PF when you should have only had 2 and 2 again... or did I miss something that was correcting for this...?
I suggest that you change your main() program (temporarily) to call get_lowest_divisor() instead of get_all_divisors(). Test the program until you're sure that get_lowest_divisor() is working properly, then main() back to calling get_all_divisors().
This way, if there are problems, you'll know where to look.