Page 1 of 1

Count The Number Of Solutions

Posted: Sat Aug 10, 2013 2:26 pm
by Fahim Shahriar
Suppose, I want to find the number of solutions of this equation $a+b+c+d=7$ ; where $a,b,c,d$ are natural numbers.

To find the solutions I wrote the following code.

Code: Select all

#include <stdio.h>

int main ()
{
  int a,b,c,d,n;
  for(a=1;a>=0 && a<=7;a++)
  {for(b=1;b>=0 && b<=7;b++)
  {for(c=1;c>=0 && c<=7;c++)
  {for(d=1;d>=0 && d<=7;d++)
  {
      n = a + b + c + d;
  if(n==7)
  {
          printf("%d %d %d %d\n",a,b,c,d);         
  }}}}}
  system("pause");
  return 0;
}
Now, add something to the code that will count the number of solutions.

Re: Count The Number Of Solutions

Posted: Sat Aug 10, 2013 10:52 pm
by rakeen
Just add a counter!

Code: Select all

int main ()
{
  int a,b,c,d,n,count=0;
  for(a=1;a>=0 && a<=7;a++){
  	for(b=1;b>=0 && b<=7;b++){
  		for(c=1;c>=0 && c<=7;c++){
  			for(d=1;d>=0 && d<=7;d++){
      			n = a + b + c + d;
  				if(n==7){
  					count++;
          			printf("%d %d %d %d\n",a,b,c,d);         
  				}
  			}
  		}
  	}
  }
  printf("%d",count);
  system("pause");
  return 0;
}

Re: Count The Number Of Solutions

Posted: Tue Jan 07, 2014 1:52 pm
by Masum
You can optimize this code. For a silly example, you don't need the condition $a>=0$ and $a<= 7$ at a time since you are starting the loop from $1$, there is no reason for $a$ to be $0$.