Write a program to arrange numbers from 1 to 16 such that the sum of two consecutive numbers is a perfect square Click for Solution |
Explore
- GPL4you
- Home
- Prepdoor - Online Mock Test
- About
- FAQs
- Contact
- Contact Us
© 2011 - gpl4you | All Rights Reserved.
Recursive solution
i in rec_sol(i) shows the length of solution obtained till now
#include <stdio.h>
int squarelist[5]={4,9,16,25};
int list[15]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
int sol[16]={16,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
void rec_sol(int);
int checkalready(int , int);
int main()
{
rec_sol(1);
return 1;
}
void rec_sol(int i)
{
int k, j;
if(i==16)
{
for(k=0;k<16;k++)
printf(" %d ",sol[k]);
printf("\n");
}
else
{
for(k=0;k<15;k++)
{
for(j=0;j<4;j++)
{
if(sol[i-1]+list[k]==squarelist[j]&&checkalready(list[k],i))
{
sol[i]=list[k];
rec_sol(i+1);
}
}
}
}
}
int checkalready(int check , int p)
{
int k;
for(k=0;k<p;k++)
{
if(check==sol[k])
return 0;
}
return 1;
}