根据用户输入查找素数的位置

时间:2015-10-17 04:58:30

标签: c++

此c ++代码打印出以下素数:3 5 7.

int main () 
{
for (int a=2; a<10; a++)
    for (int b=2; b<a; b++)
    {
        if (a % b == 0)
            break;
        else if (a == b+1)
            std::cout << a << " ";

    }
return 0;
}

我的问题是如何编程来显示素数的位置?

示例:

Enter a number : 2    
The 2th prime number is : 5

Enter a number : 3    
The 3th prime number is : 7

1 个答案:

答案 0 :(得分:0)

为此,您可以在array Like:

中存储素数
int main () 
{
int array[10];
int counter = 0;
for (int a=2; a<10; a++)
    for (int b=2; b<a; b++)
    {
        if (a % b == 0)
            break;
        else if (a == b+1)
        {
          array[counter] = a;
          counter ++;
        }
    }
for (int i=0; i<2; i++)
{
cout<<"Enter a number : ";
int position;
cin>> position;
cout<< "The "<<position<<"th prime number is "<< array[position-1]<<endl;
}
return 0;
}

输出:

Enter a number : 2    
The 2th prime number is : 5

Enter a number : 3    
The 3th prime number is : 7