Jump to content

Hi,

I recently had an assignment where I needed to take a range of numbers, find which ones were prime, and then give the prime factorization of the non prime numbers. I got a relatively good grade on the assignment, but I missed out on a few points for not having asterisks in between the prime factorization. I want to figure out how to fix this but I am a bit stumped. Here is the function in question:

int factor(int test_num)
{
  int potential_factor;

  printf("The factorization of %d is: \n", test_num);

  for(potential_factor = 2; potential_factor <= test_num;)
  {
    if(test_num % potential_factor == 0)
    {
      printf("%d ", potential_factor);

      test_num = test_num / potential_factor;
    }
      
    else
      ++potential_factor;
  }
}

This has an output like so:

image.png.2b02457fec02a1b4f558900827e82052.png

I want to make it so instead of "2 2" it would look like "2 * 2"

And also for higher numbers, like 196 for example, the factorization should look like "2 * 2 * 7 * 7"

 

How would I go about doing this without adding an extra asterisk at the end of the last number?

 

Thanks!

 

P.S. I can add the entirety of the code if you would like to look it over.

Link to comment
https://linustechtips.com/topic/986813-loop-logic-question-for-c/
Share on other sites

Link to post
Share on other sites

8 minutes ago, SgtBot said:

printf("%d ", potential_factor);

you could change that to "printf("%d *", potential_factor);

but that would also add a * at the end of the last factor.... maybe set a if statement saying if it is the last factor, : printf("%d ", potential_factor);

Link to post
Share on other sites

You could either:

  • Have it evaluate the first factor, then in the loop the first thing it does is print an asterisk.
  • Have the loop check if the exit condition fails and if it does, print an asterisk.

I prefer the first one over the second if only because the algorithm is not having to evaluate another if-statement in the loop. You just have to remember to adjust the initial value of potential_factor

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×