Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   please suggest me logic of the problem: (http://www.go4expert.com/forums/suggest-logic-t26095/)

Ankur Kamboj 20Jun2011 00:21

please suggest me logic of the problem:
 
Q:-find the all possible combination of digits ranging 1 to 9 whose sum is 10, no digit should be repeated in any combination.
e.g:
1234
127
136
145
19
235
28
37
46

priyatendulkar 20Jun2011 15:24

Re: please suggest me logic of the problem:
 
Hi,

May this s not an optimised/generalise solution ..But it produces the output as expected
The code snippet is as under:

Code:

#include<stdio.h>
int main()
{
  int i,j,k,l,sum;
  for(i = 1;i<10;i++)
  {
    sum = 0;
    for ( j=i+1 ;j<10; j++)
        {
        sum = i+j;
          if(sum == 10)
          {
            printf("%d %d\n",i,j);
            break;
          }
          if(sum > 10)
          break;
          for(k=j+1;k<10;k++)
          {
            sum = i+j+k;
          if(sum == 10)
          {
            printf("%d %d %d\n",i,j,k);
          break;
          }
          if(sum > 10)
        break;

                for ( l=k+1;l<10;l++)
                {
                    sum = i+j+k+l ;
                        if(sum == 10)
                        {
                        printf("%d %d %d %d \n",i,j,k,l);
                        break;
                        }

                }

        }
    }
  }


Ankur Kamboj 20Jun2011 15:51

Re: please suggest me logic of the problem:
 
Quote:

Originally Posted by priyatendulkar (Post 84299)
Hi,

May this s not an optimised/generalise solution ..But it produces the output as expected
The code snippet is as under:

#include<stdio.h>
int main()
{
int i,j,k,l,sum;
for(i = 1;i<10;i++)
{
sum = 0;
for ( j=i+1 ;j<10; j++)
{
sum = i+j;
if(sum == 10)
{
printf("%d %d\n",i,j);
break;
}
if(sum > 10)
break;
for(k=j+1;k<10;k++)
{
sum = i+j+k;
if(sum == 10)
{
printf("%d %d %d\n",i,j,k);
break;
}
if(sum > 10)
break;

for ( l=k+1;l<10;l++)
{
sum = i+j+k+l ;
if(sum == 10)
{
printf("%d %d %d %d \n",i,j,k,l);
break;
}

}

}
}
}

but i want it with least complexity like O(n)...


All times are GMT +5.5. The time now is 06:26.