Friday, November 19

My answer for the Prime Ring


// Problem A: Prime Ring

#include 〈 stdio.h>
#include 〈 math.h>
int ring[16];
int m;

bool NotInRing(int iPos, int iNum)
{
int i;
for(i=0; i〈 iPos; i++){
if (iNum == ring[i]){
return false;
}
}
return true;
}

int GetNumber(int iPos, int iNumber)
{
int i;
for(i=iNumber+1; i〈 =m; i++){
if (NotInRing(iPos, i))
return i;
}
return 0;


}

bool IsPrime(int iNum)
{
int i;
for (i=2; i〈 =sqrt((double)iNum); i++) //sqr/sqrt
{
if (iNum == ((int)iNum/i)*i) // (inum%i == 0)
return false;
}
return true;
}


bool FindNumber(int iPos)
{
int iNumberTwo, iTotal;
if(iPos〈 1)
return false;

if (iPos == m)
{
iTotal = ring[iPos-1] + ring[0];
if (IsPrime(iTotal))
{
for(int j=0; j〈 m; j++){
printf("%d ", ring[j]);
}
printf("\n");
return true;
}
else
return false;
}


iNumberTwo = GetNumber(iPos, 0);
while(iNumberTwo != 0){
ring[iPos] = iNumberTwo;
iTotal = ring[iPos]+ring[iPos-1];
if (IsPrime(iTotal)){

// printf("Now in %d, try %d, and %d is prime\n", iPos, ring[iPos], iTotal);
// for(int i=0; i〈 =iPos; i++)
// printf("%d ", ring[i]);
// printf("\n\n");

if (FindNumber(iPos+1) == true){
// iPos --;
}
}
iNumberTwo = GetNumber(iPos, iNumberTwo);
}
return false;
}

main()
{
int i, j, k;
// int ring[16];
ring[0] = 1;

while (scanf("%d", &m)){
if (m == 0)
break;

// printf("Get %d\n", m);
if (FindNumber(1) == true)
{
for(j=0; j〈 m; j++){
printf("%d ", ring[j]);
}
printf("\n");
}
}// end while.
}



Labels: ,