求每个n到m的约数的计算次数为:
(sqrt{n}+sqrt{n+1}+...+sqrt{m}leq(m-n+1)sqrt{m},当m=n时取等号)
时间复杂度为:(O((m-n)sqrt{m}))
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(), m = sc.nextInt();
int[] f = new int[m+5];
Arrays.fill(f, Integer.MAX_VALUE);
f[n] = 0;
for(int i=n; i <= m; i++) {
if(f[i] == Integer.MAX_VALUE) continue;
for(int j=2; j*j <= i; j++) {
if(i % j != 0) continue;
int a = j, b = i / j;
if(i+a <= m) f[i+a] = Math.min(f[i+a], f[i] + 1);
if(i+b <= m) f[i+b] = Math.min(f[i+b], f[i] + 1);
}
}
if(f[m] != Integer.MAX_VALUE)
System.out.println(f[m]);
else
System.out.println(-1);
}
}
/*
f[i] 表示到i 的最小步数
f[i] = f[k] + 1 ,i-k 是k的约数
*/