【问题标题】:Count number of digits in factorial - Input/Ouput performance issue计算阶乘中的位数 - 输入/输出性能问题
【发布时间】:2023-03-20 11:10:02
【问题描述】:

我正在解决 spoj 平台上的任务 - 计算阶乘中的位数。 我找到了 Kamenetsky 公式并实现了它:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        int numOfTests = Integer.parseInt(in.readLine());

        for(int i = 0; i < numOfTests; i++) {
            System.out.println(KamenetskyFormula(Integer.parseInt(in.readLine())));
        }

        /*
        in.lines()
                .limit(numOfTests)
                .map(n -> Integer.parseInt(n))
                .forEach(n -> System.out.println(KamenetskyFormula(n)));*/
    }

    private static long KamenetskyFormula(int n) {
        if (n < 2) {
            return 1;
        }
        double x = n * Math.log10(n / Math.E) + Math.log10(2 * Math.PI * n) / 2.0;
        return (long) (Math.floor(x) + 1);
    }
}

首先我使用了注释代码(流),因为我认为它比实际代码(没有 cmets)慢,所以我进行了更改,但仍然超过了时间限制。我怎样才能让它更快?

示例输入是(第一行是测试数):

3
1
10
100

和预期的输出:

1
7
158

【问题讨论】:

  • 我认为这段代码没有太大的改进空间。使用一些日志标识和预先计算,公式可以写成只需要一次日志计算而不是两次的形式。但是对于少量的测试用例,这并不重要。也许还有其他更有效的方法。
  • 需要多快?我做了一个快速检查,您的代码(大约)立即完成,即使添加 1000 个代码也是如此。
  • @Yonas Limit czasu wykonania programu: 0.303s 这意味着,程序执行超时:0.303s 我检查了这个任务的解决方案的历史,一个人用 Java 解决了它,所以它是可能的

标签: java algorithm math optimization factorial


【解决方案1】:

我认为由于 I/O 速度慢,时间限制已超出。这主要是因为 System.out.println 的底层 PrintStream。在此帖子why-is-system-out-println-so-slow 中查找更多详细信息。您可以参考下面的 Fast I/O 模板来帮助解决这个问题。

参考 - Fast I/O in java

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;

public class YourClassName {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskA solver = new TaskA();
        int testCount = Integer.parseInt(in.next());
        for (int i = 1; i <= testCount; i++)
            solver.solve(i, in, out);
        out.close();
    }

    static class TaskA {
        public void solve(int testNumber, InputReader sc, PrintWriter w) {
            /*your logic goes here
            use w.println here to print the output which is usually faster
            */
        }

    }

    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private InputReader.SpaceCharFilter filter;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (numChars == -1)
                throw new InputMismatchException();

            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }

                if (numChars <= 0)
                    return -1;
            }
            return buf[curChar++];
        }

        public int nextInt() {
            int c = read();

            while (isSpaceChar(c))
                c = read();

            int sgn = 1;

            if (c == '-') {
                sgn = -1;
                c = read();
            }

            int res = 0;
            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));

            return res * sgn;
        }

        public long nextLong() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            long res = 0;

            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public String readString() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            StringBuilder res = new StringBuilder();
            do {
                res.appendCodePoint(c);
                c = read();
            } while (!isSpaceChar(c));

            return res.toString();
        }

        public boolean isSpaceChar(int c) {
            if (filter != null)
                return filter.isSpaceChar(c);
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public String next() {
            return readString();
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);

        }

    }
}

【讨论】:

  • 不幸的是:static class TaskA { public void solve(InputReader sc, PrintWriter writer) { writer.println(KamenetskyFormula(Integer.parseInt(sc.next()))); } }仍有时间限制超过;/
  • 您不应该使用 sc.nextLong() 而不是 sc.next() 吗?因为读取字符串并转换为 Integer 是开销
  • 它成功了!谢谢@Darshil Dave! writer.println(KamenetskyFormula(sc.nextLong()));
猜你喜欢
  • 2021-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-14
  • 2011-04-26
相关资源
最近更新 更多