如何在给定的 this 中找到最大模数

How to find greatest modulo in a given this

我想做的是在列表中找到最大的模数

到目前为止,这是我的代码:

import java.util.*;

public class p2 {

    public static void main(String[] args) {
        ArrayList<Integer> ar = new ArrayList<>();
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int m = sc.nextInt();
        for(int i = 1; i <= n; i++) {
            int mod = i % m;
            ar.add(mod);
        }
        System.out.println(Collections.max(ar));    
    }
}

例如

5 3

输出为 2

因为1-5除以3的最大模数是2

有没有不使用蛮力的更快的方法?

1-n 范围内的所有数字中,m 的最大模数是 m - 1,除非 n < m,在这种情况下它是 n,所以:

int maxModulo = Math.min(n, m-1);

以上当然是假设n >= 1m >= 1.