I wanted to know how I can print the decomposition of a number into factors in a single line, because in my case when the divisor changes, it prints a new line, i.e:
392 = 2^3 * 7^2
And not:
392 = 2^3
392 = 7^2
#include <iostream>
int main() {
int n, dig, num, i, val;
do {
std::cout << "Enter a number greater than one: ";
std::cin >> n;
} while (n <= 1);
i = 2;
val = 0;
num = n;
do {
dig = num % i;
if (dig == 0) {
do {
num = num / i;
dig = num % i;
val = val + 1;
} while (dig == 0);
std::cout << n << " = " << i << "^" << val << std::endl;
}
val = 0;
i = i + 1;
} while (num != 1);
return 0;
}
You're doing the stuff a bit too complicated at some points on the one hand while you missed some (minor?) issues on the other hand...
A very simple approach could instead look like this:
The
separatorvariable serves for printing=the first time a value is found and*otherwise. Just exchanging the pointer on need is a much simpler – and much more efficient – approach than branching within the loop (std::cout << (alreadyFound ? " * " : " = ")).Further optimisations comprise on the one hand the outer loop; testing for
i*i <= navoids testing values ofithat cannot be a factor of the remainingnanyway – however, as shown above, we do not findnitself if that one's getting a prime number, so we need to handle that separately. Ifngets 1 in the meanwhile – never mind,i*iwill still remain larger, so that's actually covered.The second optimisation, on the other hand:
is fully equivalent to
The first time the loop condition is tested cover's the original
if– if the condition isn't met already now the loop simply won't be entered either...Note that this is entirely untested code – if you find a bug, please fix yourself.
Just as a side note:
for(int i = 2; i*i <= n; ++i)is, apart from the test fori*i < n(the modified number), the most primitive variant you might chose. You could still optimise, but this will result in more complex code - you have the same choices for as when testing for prime numbers (you'll find references here on SO as well). Least complex of these optimisations (with least performance boost): Calculate 2 separately before the loop and then havefor(int i = 3; i*i <= n; i += 2)...