Only the function is written below
Function of prime factors
void prime(int x) {
int i, j;
wrote this because it wanted for information but don't have any
for (i = 2; i <= x; i++) {
if (x % i == 0) {
for (j = 2; j <= i; j++) {
if (i == j) {
printf("%d", i);
} else
if ((i % j) != 0) {
printf("%d\n", i);
The output should be prime numbers of the number and the repeated prime no.s also should be seen so by mutiplication we get the original number
goto l;
Here the goto statement takes out of if loop
} else {
break;
}
}
l:
x = x / i;
}
}
}
Code seems to be correct and also is giving the prime numbers but is the factors are not repeating itself.
for e.g: 24 output should be 2,2,3 but the output is coming as 2,3
The
gotostatement is useless, it is exactly equivalent to abreakstatement in your case. It does not break out of theifloop, it breaks out of theforloop, which is exactly whatbreakdoes.Furthermore, the inner loop is useless: if you divide
xbyi, you effectively remove the smaller primes fromx, andx % i == 0will hold only for prime values ofi.The problem in the output comes from the fact that you increment
ieven ifxis a multiple ofi. Therefore you only print a prime factor once and you do not remove it completely fromx.The function can thus be simplified into:
The function can be made much faster: you can stop the scan when
iis greater than the square root ofx: