Search code examples
cprime-factoring

problem in prime algorithm in C


Following the answer from @neal aise here to get prime factors: I did:

/*neal aise's  code*/
printPrimeFactors(int num) {
  int i;
  for (i = 2; i < sqrt(num); i=next_prime(i)) {
     if (num %i){
        printf("%d", i);
     }
  } 
}

/*my code*/
int next_prime(int p){
   int prime_found = 0; 
   while (!prime_found){
    if (p <= 1)/* if low number comes in, then */
       p = 2; /* next prime is always 2 (first prime) */
    else
          if ((p % 2) == 0) /* no even primes */
              p++;      /* make the number odd before test */
          else
              p += 2;       /* get next odd numero to test */
    prime_found = is_prime(p); /*check if number is prime*/
    }
    return (p);
}


int is_prime(int p){
    int curr_num = 2;                  /* start divisor at 2 */
    float stop_num = sqrt((float) p);  /* no divisor > sqrt of number needed */    
    while(curr_num <= stop_num){
        if ((p % curr_num) == 0)      /* not prime if evenly divisible */
            return (0);
        else
            curr_num++;              /* increment divisor */
    }
    return(1);                         /* not evenly divisible, return prime */
}

How do I moddify the code in function

printPrimeFactors()

so it works as desired?


Solution

  • If you want "prime number generator", interfaces is ok to me. But your code limit the number of prime numbers.

    meaningless interfaces is not valuable. it can write more simply.

    #include <stdio.h>
    
    int main() {
      int n, m;
      for (n = 1; n < 1000 /* specify your max */; n++) {
        for (m = n-1; m > 1; m--)
          if (n % m == 0) break;
        if (m == 1)
          printf("%d\n", n);
      }
      return 0;
    }