数字游戏

递归过不了数据 卷子交完才想起来可以用动态规划 难过。。。

数字游戏

给定一个数字 若可以开方 则去开方 否则减一 循环次操作 多少次后数字变为1?

递归

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
let res = 0
function numberGame(num){
if(num==1){
return res
}
let nextparam
let n = Math.sqrt(num)
if(Math.floor(n)==n){
nextparam = n
}else{
nextparam = n-1
}
res++
numberGame(nextparam)
}

动态规划

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function numberGameDP(num){
let dp = []
dp[0] = 0
dp[1] = 0
for(let i=2;i<=number;i++){
let c = Math.sqrt(num)
if(c == Math.floor(c)){
dp[i] = dp[c]+1
}else{
dp[i] = dp[i-1]+1
}
}
console.log(dp[num])
return dp[num]
}