大約在一千五百年前,大數學家孫子在《孫子算經》中記載了這樣的一道題:“今有雛兔同籠,上有三十五頭,下有九十四足,問雛兔各幾何?
private static final int head = 35; // 頭有35個
private static final int foot = 94; // 腳有94個
private static final int chicken = 2; // 雞有2只腳
private static final int rabbit = 4; //兔有4只腳
public static void main(String[] args) {
int count_ck,count_rb;
for(count_ck=0;count_ck<foot/2;count_ck++){
for(count_rb=0;count_rb<foot/4;count_rb++){
if((count_rb+count_ck==head) && (count_rb*4+count_ck*2==94)){
System.out.println("雞:"+count_ck);
System.out.println("兔:"+count_rb);
}
}
}
}
結果:
雞:23
兔:12