Count The Number Of Solutions

Discuss Computer Science and Programming related problems

Moderators:Labib, bristy1588

User avatar
Fahim Shahriar
Posts:138
Joined:Sun Dec 18, 2011 12:53 pm
Count The Number Of Solutions

Unread post by Fahim Shahriar » Sat Aug 10, 2013 2:26 pm

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.
Name: Fahim Shahriar Shakkhor
Notre Dame College

User avatar
rakeen
Posts:384
Joined:Thu Dec 09, 2010 5:21 pm
Location:Dhaka

Re: Count The Number Of Solutions

Unread post by rakeen » Sat Aug 10, 2013 10:52 pm

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;
}
r@k€€/|/

User avatar
Masum
Posts:592
Joined:Tue Dec 07, 2010 1:12 pm
Location:Dhaka,Bangladesh

Re: Count The Number Of Solutions

Unread post by Masum » Tue Jan 07, 2014 1:52 pm

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$.
One one thing is neutral in the universe, that is $0$.

Post Reply