hdu 1216 Assistance Required

傳送門

After the 1997/1998 Southwestern European Regional Contest (which was held in Ulm) a large contest party took place. The organization team invented a special mode of choosing those participants that were to assist with washing the dirty dishes. The contestants would line up in a queue, one behind the other. Each contestant got a number starting with 2 for the first one, 3 for the second one, 4 for the third one, and so on, consecutively.
The first contestant in the queue was asked for his number (which was 2). He was freed from the washing up and could party on, but every second contestant behind him had to go to the kitchen (those with numbers 4, 6, 8, etc). Then the next contestant in the remaining queue had to tell his number. He answered 3 and was freed from assisting, but every third contestant behind him was to help (those with numbers 9, 15, 21, etc). The next in the remaining queue had number 5 and was free, but every fifth contestant behind him was selected (those with numbers 19, 35, 49, etc). The next had number 7 and was free, but every seventh behind him had to assist, and so on.

Let us call the number of a contestant who does not need to assist with washing up a lucky number. Continuing the selection scheme, the lucky numbers are the ordered sequence 2, 3, 5, 7, 11, 13, 17, etc. Find out the lucky numbers to be prepared for the next contest party.

Input

The input contains several test cases. Each test case consists of an integer n. You may assume that 1 <= n <= 3000. A zero follows the input for the last test case.

Output

For each test case specified by n output on a single line the n-th lucky number.

Sample Input

1
2
10
20
0

Sample Output

2
3
29
83

【題意】

開始有一個從2開始的自然數序列,開始如下操作,取出該序列中的第一個數字,作爲新序列中的數字,假設該數字是a,然後刪除原序列中第a個數字,第2a個數字……一直這樣操作,這樣會生成一個新序列,然後每次詢問你新序列中某一項是多少。

【分析】

直接模擬即可,也可以提前將表打出來,然後把表交上去,前者耗時240Ms,後者代碼長度大。

【代碼】

#include <iostream>
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<math.h>
#include<cmath>
#include<map>
#include<time.h>
#include<bits/stdc++.h>
using namespace std;
const int maxm = 4e4;
bool num[maxm];
int ans[maxm];
int main()
{
//    freopen("in.txt","w",stdout);
    memset(num,false,sizeof(num));
    int flag = 1;
    for(int i = 2;i<maxm;i++)
    {
        if(!num[i])
        {
            ans[flag++] = i;
            int x = 0;
            int now = i+1;
            while(now<maxm)
            {
                if(!num[now])
                {
                    x++;
                    if(x==i)
                    {
                        num[now] = true;
                        x = 0;
                    }
                }
                now++;
            }
        }
    }
    int a;
    while(scanf("%d",&a),a)
    {
        printf("%d\n",ans[a]);
    }
    return 0;
}




發佈了182 篇原創文章 · 獲贊 5 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章