An introduction to the C + + algorithm race Classic Page9 example 1-4 chicken and rabbit cage

Source: Internet
Author: User

Title: Total number of chickens and rabbits: N, total number of legs: M. input n,m, output the number of chickens and rabbits respectively; no solution output "no answer"

Sample Output 1:

14 32

Sample Output 1:

12 2

Sample Input 2:

10 16

Sample Output 2:

No Answer

First, declare two variables n,m corresponding total and total leg number, and then declare two variables for the number of chickens and rabbits each, a, b

1 int n,m,a,b;

Input n,m:

scanf ("%d%d", &n,&m);

Through simultaneous equations:

A+b=n

2a+4b=m

Have

A= (4n-m)/2; b=n-a;

Determine if there is no solution:

1. The total leg number m cannot be odd

2.a>=0

3.b>=0

The

if (m%2= =1| | a<0| | b<0)    printf ("No answer");

If there is a solution, the output is a, B:

Else     printf ("%d%d", A, b);

Full code:

//P9 case 1-4 chicken and rabbit cage#include <cstdio>intN,m;//N: Total m: Total number of legsintMain () {intb;//A: The number of chickens B: the number of rabbitsscanf ("%d%d", &n,&m);//total number of inputs N and total number of legs Ma=(4*N-M)/2;//simultaneous equations 2a+4b=m and A+b=nb=n-A; if(m%2==1|| a<0|| b<0)//The total number of legs cannot be odd and the number of chickens and rabbits cannot be negative.printf"No Answer"); Elseprintf ("%d%d", A, b); return 0; } 

An introduction to the C + + algorithm race Classic Page9 example 1-4 chicken and rabbit cage

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.