2009年2月22日 星期日

Q10015: Joseph's Cousin

/*
質數選法用sieve
要讓跑的次數少一點
不然會很沒有效率
Run time: 0.030
*/
#include <stdio.h>
#define N 32610
int prime[3500];
bool isprime[N];
void assignPrime();
int test(int n);

int main()
{
assignPrime();
int n;
int survivor;
while (scanf("%d", &n))
{
if (!n) break;

survivor = test(n);
printf("%d\n", survivor);
}
return 0;
}

void assignPrime()
{
int i, j;

for ( i = 2; i*i <= N; i++)
if (!isprime[i])
for ( j = 2*i; j <= N; j+=i)
isprime[j] = true;

for ( i = 2, j = 0; i <= N; i++)
if (!isprime[i])
prime[j++] = i;
}

int test(int n)
{
int left = n;
int count;
int index = 0;
int i, j;
bool arr[n];

for ( i = 0; i < n; i++)
arr[i] = true;

for ( i = 0; i < n-1; i++)
{
count = (left < prime[i]) ? prime[i]%left : prime[i];

for ( j = 0; j < count; index++)
{
if (index == n)
index = 0;

if (arr[index])
j++;
}

arr[--index] = false;
index++;
left--;
}

for ( i = 0; i < n; i++)
if (arr[i])
return (i+1);
}

沒有留言: