I posted this thread but it got transferred to another, can someone edit the code for me so that I can get the answer in exponentiation, (^)and(*),

Example :

Enter number : 8
Prime factors of '8' : 2^3

Enter number : 56
Prime factors of '56' : 2^3*7

Not

Enter number : 8
Prime factors of '8' : 2*2*2

Enter number : 56
Prime factors of '56' : 2*2*2*7


This can really save lots of trouble. Please help me with this, Thanks!

#include <stdio.h>

/* Find out the prime factors
 * of a given number and print
 * them on the screen */
void factorize(int n)
{
  int d = 2;
  
  if(n < 2) return;
  
  printf("Prime factors of '%d': ", n);
  /* while the factor being tested
   * is lower than the number to factorize */
  while(d < n) {
    /* valid prime factor */
    if(n % d == 0) {
      printf("%d * ", d);
      n /= d;
    }
    /* invalid prime factor */
    else {
      if(d == 2) d = 3;
      else d += 2;
    }
  }
   
  /* print last prime factor */
  printf("%d\n", d);
}

#if defined TEST_DRIVER && TEST_DRIVER > 0
void factorize_test(void)
{
  int i;
  for(i = 0; i < 50; i++) {
	factorize(i);
  }
}

int main(void)
{
  factorize_test();
  return 0;
}
#else
int main(void)
{
  int number;
  
  do {
    printf("Enter number: ");
    scanf("%d", &number);
    factorize(number);
  } while (number > 1);
  
  return 0;
}
#endif

Recommended Answers

All 5 Replies

create an arraay.
increment first element each time you encounter a two, second element each time u encounter a three so on. Then you have the individual counts of each factor.
Also check till sqr. root of n. saves time.

create an arraay.
increment first element each time you encounter a two, second element each time u encounter a three so on. Then you have the individual counts of each factor.
Also check till sqr. root of n. saves time.

Sorry I don't really catch what you mean, can you explain more in detail?

Around a week ago..some one posted a very similar question and it was answered (debated) in much detail. Just search for the question in the C forum

I saw the question before but it went off topic and instead they were debating on two algorithm and it wasn't really helpful to a beginner to me, I tried to search on how to put the exponentiation but I couldn't find it. It would be helpful if someone help me with this.

Well how about this : Create an array of size n. Then run the algorithm. Each time you find a factor p, increment arr[p] by 1.

Then run a for loop from 1 to n check to see if arr is 0 or not. If it is 0 then ignore it else o/p i^arr

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.