生成随机数并检查素数的数量

时间:2014-07-31 09:09:40

标签: c

我想创建一个生成随机数的程序,然后要求用户输入已生成的素数。如果数字正确,则用户被宣布为胜利者,否则,失败。请帮忙。

2 个答案:

答案 0 :(得分:3)

使用标头srand中声明的标准C函数rand<stdlib.h>生成随机数。然后编写一个函数来确定给定的数字是否是素数。考虑到1不是素数。您可以在stackoverflow中找到许多此类函数的示例。

祝你好运!:)

答案 1 :(得分:1)

试试这段代码 -

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

示例输出 -

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!
相关问题