今有雞兔同籠,上有35個頭,下有94只腳,問雞兔各有多少只?
// 雞兔同籠問題方法1
- (void)jiTuTongLongMethod2 {
/**
解題思路:
x+y=h
2x+4y=f
消元法
x=(4h-f)/2
y=(f-2h)/2
*/
// 頭,腳,雞
int h = 35,f = 94,x;
x = (4 * h - f) / 2;
if (x > 0 && x < h && 2 * x == 4 * h - f) {
NSLog(@"雞有%d只,兔有%d只",x,h - x);
} else {
NSLog(@"無解");
}
}
// 雞兔同籠問題方法1
- (void)jiTuTongLongMethod1 {
// 頭
NSInteger headCount = 35;
// 腳
NSInteger foot = 94;
BOOL temp = NO;
for (int i = 1; i < headCount; i++) {
if ( i * 2 + (headCount - i) * 4 == foot ) {
NSLog(@"雞有%d只,兔有%ld只",i,(headCount - i));
temp = YES;
}
}
if (temp == NO) {
NSLog(@"問題無解");
}
}