【枚举算法】解不等式

来源:互联网 发布:人力资源软件排名2016 编辑:程序博客网 时间:2024/05/17 07:36

解不等式:

m1 < 1/2 + √2/3 + ... + √n/(n+1) < m2


算法分析:

这里正整数的m1和m2从键盘输入

设和s和递增变量index的初始值为0。

在s <= m1的循环中,根据递增变量index对s累加求和,直至出现s > m1,退出循环,确定n的下限minIndex = index。

同理求出n的下限maxIndex = index - 1。


代码实现:

package cn.qblank.enumeration;import java.util.Scanner;/** * 解不等式 m1 < 1/2 + √2/3 + ... + √n/(n+1) < m2 * @author Administrator */public class Demo3 {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.println("请输入正整数m1:");long m1 = input.nextLong();System.out.println("请输入正整数m2:");long m2 = input.nextLong();input.close();int index = 0;//定义中间分数之和double s = 0;while(s < m1){index++;s = s + Math.sqrt(index)/(index + 1);}long minIndex = index;do{index++;s += Math.sqrt(index)/(index + 1);}while(s < m2);long maxIndex = index - 1;System.out.println("满足不等式的正整数n为:" + minIndex +"≤n≤" + maxIndex);}}

运行结果如下: