查找分子或分母不大于一亿的分数Π


    private static final int MAX_N = 100000000;

    private static void findPIByDivider() {
        Log.d("findPI", "findPIByDivider start MAX_N=" + MAX_N);
        long curtime = System.currentTimeMillis();
        double lastRet = 1;
        int selectI = 0, selectJ = 0;
        double finalRet = 0;
        for (int i = 3; i <= MAX_N; i++) {
            int m = (int) (i / Math.PI);
            for (int j = m; j <= m + 1; j++) {
                double di = i;
                double ret = Math.abs(di / j - Math.PI);
                if (ret < lastRet) {
                    lastRet = ret;
                    selectI = i;
                    selectJ = j;
                    finalRet = di / j;
                }
            }

            if( isPowerOfTen(i) || i == MAX_N) {
                Log.d("findPI", "i=" + String.format("%-12s", i) + " fraction = " + String.format("%12s", selectI) +
                        " / " + String.format("%-12s", selectJ) + " finalRet=" + finalRet);
            }

        }
        Log.d("findPI", "findPIByDivider end. PI=" + Math.PI + " use time=" + (System.currentTimeMillis() - curtime));
    }

    private static void findPIByMulti() {
        Log.d("findPI", "findPIByMulti start MAX_N=" + MAX_N);
        long curtime = System.currentTimeMillis();
        double lastRet = 1;
        int selectI = 0, selectJ = 0;
        double finalRet = 0;
        for (int i = 1; i <= MAX_N; i++) {
            int m = (int) (i * Math.PI);
            for (int j = m; j <= m + 1; j++) {
                double di = i;
                double ret = Math.abs(j / di - Math.PI);
                if (ret < lastRet) {
                    lastRet = ret;
                    selectI = i;
                    selectJ = j;
                    finalRet = j / di;
                }
            }

            if( isPowerOfTen(i) || i == MAX_N) {
                Log.d("findPI", "i=" + String.format("%-12s", i) + " fraction = " + String.format("%12s", selectJ) +
                        " / " + String.format("%-12s", selectI) + " finalRet=" + finalRet);
            }
        }
        Log.d("findPI", "findPIByMulti end. PI=" + Math.PI + " use time=" + (System.currentTimeMillis() - curtime));
    }

    private static boolean isPowerOfTen(int num) {
        int tenPower = 1;
        for (int i = 1; i < 12; i++) {
            tenPower *= 10;
            if (num == tenPower) {
                return true;
            }
        }
        return false;
    }

结果如下:

反复运行后,会发现在做大量运算时,乘法要比除法的效率高一些

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部