一道java编程题

2025-02-25 10:29:33
推荐回答(2个)
回答1:

用两个map存储中间计算的过程数据,可以提高执行效率

import java.util.HashMap;
import java.util.Map;

public class $ {

    private static Map jiechengMap = new HashMap();
    private static Map snMap = new HashMap();

    public static void main(String[] args) {

        int i = 2;
        double lastValue = 0;
        double result;
        while (true) {
            result = getResult(i);
            if (result - lastValue <= 0.00001) {
                System.out.println("差少于0.00001是的N是:" + i);
                System.out.println(jiechengMap);
                System.out.println(snMap);
                return;
            } else {
                i += 2;
                lastValue = result;
            }
        }
    }

    private static double getResult(long num) {

        if (num <= 0) {
            snMap.put(0L, 0D);
            return 0;
        }
        Double tmp = snMap.get(num);

        if (tmp != null) {
            return tmp;
        }

        long jiecheng = getJiecheng(num);

        tmp = getResult(num - 2) + 1.0 / jiecheng;

        snMap.put(num, tmp);

        return tmp;
    }

    private static long getJiecheng(long num) {

        Long result = jiechengMap.get(num);

        if (result != null) {
            return result;
        }

        if (num <= 1) {
            jiechengMap.put(num, 1L);
            return 1L;
        }

        result = getJiecheng(num - 1) * num;
        jiechengMap.put(num, result);

        return result;
    }
}
差少于0.00001是的N是:10
{1=1, 2=2, 3=6, 4=24, 5=120, 6=720, 7=5040, 8=40320, 9=362880, 10=3628800}
{0=0.0, 2=0.5, 4=0.5416666666666666, 6=0.5430555555555555, 8=0.5430803571428571, 10=0.5430806327160493}

回答2:

   public static void main(String[] args) throws Exception {
       
       System.out.println(nn(8000));

   }
   public static int nn(int n){
       if(ss(n+2)-ss(n)<0.00001){
  System.out.println(ss(n+2)-ss(n));
  return n;
       };
       return nn(n+2);
   }
   public static double ss(int n){
       if(n>0){
 return 1d/n+ss(n-2);
       }
       return 0;
   }
以上代码是根据你的公式写的,不过以上代码嵌套循环太多,如果jvm内存不够,会溢出。

另外如果这是一个面试题的话,不是要求算法那么直接给出答案就是99998

s(n)=1/2+1/4+1/6+1/8.......+1/n
s(n+2)-s(n) 其实等于1/(N+2) <0.00001  也就是1/100000   所以n=99998