-9

I want to create a program that generates random numbers and then asks a user to enter number of prime numbers that have been generated. If the number is correct, the user is declared winner, else, loses. Please help.

Mwangi Thiga
  • 1,339
  • 18
  • 22
  • 3
    "Please help" with what? What's your question? – kviiri Jul 31 '14 at 09:11
  • 1
    I think the question is "can you please do my home work?" – jpo38 Jul 31 '14 at 09:12
  • 1
    OK, thank you to share your wishes. What's your question? A question to be on-topic on SO must describe a specific problem, what you tried to solve it and where you stopped. _"These are my requirements, what to do?"_ questions are off-topic. I'd also suggest to read FAQ before asking. – Adriano Repetti Jul 31 '14 at 09:12
  • Was simply asking for a C code – Mwangi Thiga Jul 31 '14 at 09:23
  • Propose a code with a problem and we can help you fixing it. But nobody's going to do the work for you from scratch... – jpo38 Jul 31 '14 at 09:25
  • @user3501133: Check out for random number :http://stackoverflow.com/questions/822323/how-to-generate-a-random-number-in-c . Since the prime numbers are probably reasonably small I would just brute force if they are prime. – Lucas Jul 31 '14 at 09:26

2 Answers2

3

Use standard C functions srand and rand declared in header <stdlib.h> to generate random numbers. Then write a function that determinates whether a given number is a prime number. Take into account that 1 is not a prime number. You can find yourself many examples of such functions here at stackoverflow.

Good luck!:)

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
1

Try this code-

#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<unistd.h>
int main()
{
    int arr[10], i, j, n, count=0;
    srand(getpid()); //Every time it will give the different seed to rand(), so you wont get same array again and again
    for (i = 0; i < 10; i++)
        arr[i] = (rand()%100) + 1;

    printf("Enter the No of prime numbers!\n");
    scanf("%d", &n);

    for (i = 0; i < 10; i++) {
        for (j = 2; j < arr[i]; j++)
            if (arr[i]%j == 0)
                break;
        if (arr[i] == j)
            count++;
    }
    printf("Prime Num in Array = %d, User I/p = %d\n",count,n);
    if(count == n)
        printf("Yeah! You have guessed correctly!\n");
    else
        printf("Sorry! Try again!\n");
    return 0;
}

Sample output-

root@ubuntu:~/c/basics# ./a.out 
Enter the No of prime numbers!
3
Prime Num in Array = 1, User I/p = 3
Sorry! Try again!
root@ubuntu:~/c/basics# ./a.out 
Enter the No of prime numbers!
2
Prime Num in Array = 2, User I/p = 2
Yeah! You have guessed correctly!
Sathish
  • 3,740
  • 1
  • 17
  • 28