开发者

problem in prime algorithm in C

开发者 https://www.devze.com 2023-03-14 08:29 出处:网络
Following the answer from @neal aise here to get prime factors: I did: /*neal aise\'scode*/ printPrimeFactors(int num) {

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?


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;
}


There are a couple of logic errors:

if (num%i) // Change this to...
if ((num%i)==0) // num%i == 0 when i divides num, this 'i' is a prime factor.

Also, you will only print out roughly half of the prime factors by stopping at <sqrt(num). Either change the exit condition of the for loop to be i <= num:

for (i = 2; i <= num; i=next_prime(i)) { // note the <=
  if (num %i){
     printf("%d ", i);
  }
}

Or the alternative, more efficient method. Note the factors will not be in order:

for (i = 2; i <= sqrt(num); i=next_prime(i)) {
  if (num %i){
     printf("%d %d ", i, num/i); // Print out the pair, since we stop at i<=sqrt(num)
  }
}


Instead of x = sqrt(n_limit) and if(n < x), you can do it like if(n*n < n_limit). No need for expensive sqrt(), floats or casts.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号