Skip to content

Commit 5e8294b

Browse files
authored
CountMinSteps_iterative.py file has been created.
1 parent 8ea294c commit 5e8294b

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# QUESTION : Given a positive integer 'n', find and return the minimum number of steps
2+
# that 'n' has to take to get reduced to 1. You can perform
3+
# any one of the following 3 steps:
4+
# 1.) Subtract 1 from it. (n = n - ­1) ,
5+
# 2.) If n is divisible by 2, divide by 2.( if n % 2 == 0, then n = n / 2 ) ,
6+
# 3.) If n is divisible by 3, divide by 3. (if n % 3 == 0, then n = n / 3 ).
7+
8+
# Now solve this iteratively :
9+
10+
from sys import stdin
11+
from sys import maxsize as MAX_VALUE
12+
13+
14+
15+
def countMinStepsToOne(n,dp) :
16+
dp[0] = 0
17+
dp[1] = 0
18+
i = 2
19+
while i<=n:
20+
ans1 = dp[i-1]
21+
ans2 = i-1
22+
if i%2 == 0:
23+
ans2 = dp[i//2]
24+
ans3 = i-1
25+
if i%3 == 0:
26+
ans3 = dp[i//3]
27+
ans = 1 + min(ans1,ans2,ans3)
28+
dp[i] = ans
29+
i += 1
30+
return dp[n]
31+
32+
33+
#main
34+
n = int(stdin.readline().rstrip())
35+
dp = [-1 for i in range(n+1)]
36+
print(countMinStepsToOne(n,dp))

0 commit comments

Comments
 (0)