i'm trying to write a program that print the prime factors of a given number, but i need to print them separeted by *
, for example: for the input 100 the output will be: 2*2*5*5, any suggestions? i did this so far:
# include <stdio.h>
# include <math.h>
void decomposicao(int n)
{
printf("%d = ", n);
while (n%2 == 0)
{
n = n/2;
printf("* %d ", 2);
}
for (int i = 3; i <= sqrt(n); i = i+2)
{
while (n%i == 0)
{
n = n/i;
printf("* %d ", i);
}
}
if (n > 2)
printf ("* %d ", n);
}
int main()
{
int n;
scanf("%d", &n);
if (n<=0||n==1)
{
printf("Error", n);
}
else
{
decomposicao(n);
}
return 0;
}
For this code the output is :
100 = *2*2*5*5
Add a boolean variable that tells you whether you're printing the first factor or not.
#include <stdbool.h>
void decomposicao(int n)
{
bool first = true;
printf("%d = ", n);
while (n%2 == 0)
{
n = n/2;
if (!first)
printf("* ");
printf("%d ", 2);
first = false;
}
for (int i = 3; i <= sqrt(n); i = i+2)
{
while (n%i == 0)
{
n = n/i;
if (!first)
printf("* ");
printf("%d ", i);
first = false;
}
}
if (n > 2) {
if (!first)
printf("* ");
printf ("%d ", n);
}
}