Reputation: 344
#include <stdio.h>
int factor_power(int n,int d);
int main()
{
int input;
do
{
printf("Enter an integer (> 1): ");
scanf("%d",&input);
}while(input<2);
printf("%d = ", input);
int current=input;
int i;
for(i=2; i<=current; i++)
{
int power=power_factor(current,i);
if(power!=0)
{
current=(int) (current/pow(i, power));
printf("%d^%d * ",i,power);
}
}
return 0;
}
int power_factor(int n, int d)
{
int power=0;
if(d<=n)
{
while(n%d==0)
{
power++;
n=n/d;
}
return power;
}
return 0;
}
Hello, I am new to C. I have a problem with the output of the code above. If you run the code you will see there is a extra * at the end of the output. Since C doesnt have a string class, how could I get rid of the * at the end. I know appending string is a options but is there a quicker and efficient way of solving this problem?
Upvotes: 1
Views: 61
Reputation: 23058
Print the *
in an alternative way.
int current=input;
int i;
int first_term = 1;
for(i=2; i<=current; i++)
{
int power=power_factor(current,i);
if(power!=0)
{
current=(int) (current/pow(i, power));
if (!first_term)
printf(" * ");
first_term = 0;
printf("%d^%d",i,power);
}
}
Upvotes: 2