题目链接:
https://www.nowcoder.com/practice/4284c8f466814870bae7799a07d49ec8?tpId=85&&tqId=29852&rp=1&ru=/activity/oj&qru=/ta/2017test/question-ranking
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int[] step = new int[m + 1];//令步数与石块的下标对齐
for(int i = 0; i < m + 1; i++){
step[i] = Integer.MAX_VALUE;//设置一个默认值,表示达不到这块石板
}
step[n] = 0;//从n开始,那么n到n的步数为0
for(int i = n; i < m; i++){
if(step[i] == Integer.MAX_VALUE){//表示达不到这块石板
continue;//继续这个循环
}
List<Integer> list = div(i);//存储约数
for(int j : list){//j就是div方法所求的约数
if(i + j <= m && step[i + j] != Integer.MAX_VALUE){
//表示能达到这块石板,更新step[i + j]
step[i + j] = Math.min(step[i + j], step[i] +1);
}else if(i + j <= m){
step[i + j] = step[i] + 1;
}
}
}
if(step[m] == Integer.MAX_VALUE){
System.out.println(-1);
}else{
System.out.println(step[m]);
}
}
public static List<Integer> div(int num){
List<Integer> list = new ArrayList<>();
for(int i = 2; i <= Math.sqrt(num); i++){
if(num % i == 0){
list.add(i);
if(num / i != i){
list.add(num / i);
}
}
}
return list;
}
}