random primes in C

Asked

Viewed 382 times

0

I have to make a program capable of generating automatically and randomly 100 positive integers between 0 and 1000 and that presents in the console the sum and average of the primes existing in the created set.

My code is like this and when I want to show a prime number appears many repeated numbers:

#include <stdio.h>
#include <stdlib.h>
#include<time.h>

 int main(int argc, char *argv[]) {

    int number, i, counter, sum, num_divider = 0, divider;
    float media;

    srand(time(NULL));

    for (i = 0; i < 100; i++)
    {
        number = rand() % 1000;

         for(divider = 1; divider <= 1000; divider++)
            {
              if(number % divider == 0)
              {
                num_divider++;
              }



                if(num_divider < 2)
                {
                    sum += number;
                     printf("%02dº gerado %d\n", (i + 1), number);

                    printf("%d", number);

                    counter++;
                }

                num_divider = 0; 
            }

    }

    media = sum / counter;

    puts("");
    printf(" the sum is: %d\n", sum);
    printf(" the average is: %.0f\n", media);       

}
  • This has probably already been answered in one of these: https://answall.com/search?tab=votes&q=%5bc%5d%20primo

  • The title it has is misleading, because it gives the idea that it wants to generate only primes randomly. I suggest you change it and make it more appropriate about what you’re actually being asked.

  • To avoid repetition you have to store (e.g. in an array) all the primes already generated and to each new prime compare it with those already registered. If not already in the relationship then add it otherwise generate a new.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.