穷举算法



package com.xj.www.algo;
import java.util.Scanner;
/**
 * 穷举算法
 * @author xiongjing
 *
 */
public class AlgorithmTest {
      // chichen鸡的个数,rabbit兔的个数
      static int chichen, rabbit;
      // 算法具体实现
      public static int qiongJu(int head, int foot) {
            int re, i, j;
            re = 0;
            for (i = 0; i <= head; i++) {
                  j = head - i;
                  // 鸡的脚+兔的脚=总数量
                  if (i * 2 + j * 4 == foot) {
                        re = 1;
                        chichen = i;
                        rabbit = j;
                  }
            }
            return re;
      }
      // 程序主入口
      public static void main(String[] args) {
            int re, head, foot;
            System.out.println("穷举算法求解鸡兔同笼问题:");
            System.out.println("请输入头数:");
            @SuppressWarnings("resource")
            Scanner sc = new Scanner(System.in);
            head = sc.nextInt();
            System.out.println("请输入脚数:");
            foot = sc.nextInt();
            re = qiongJu(head, foot);
            if (re == 1) {
                  System.out.println("鸡有" + chichen + "只,兔有" + rabbit + "只");
            } else {
                  System.out.println("无法求解");
            }
      }
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。