मान लीजिए हमारे पास एक संख्या N है। हमें वह सबसे बड़ा पूर्ण घन निर्धारित करना है जिसे संख्या से न्यूनतम अंक हटाकर (संभवतः 0) उत्पन्न किया जा सकता है। हम दिए गए संख्या से किसी भी अंक को हटा सकते हैं। जैसा कि हम जानते हैं, एक संख्या N पूर्ण घन कहलाती है यदि N = M³ किसी पूर्णांक M के लिए।
इसलिए, यदि इनपुट 806 है, तो आउटपुट 8 होगा, क्योंकि हम 0 और 6 को हटाकर 8 प्राप्त कर सकते हैं, जो 2 का पूर्ण घन है।
समाधान दृष्टिकोण
इसे हल करने के लिए हम निम्न चरणों का पालन करेंगे:
preProcess()फ़ंक्शन परिभाषित करें जोnलेता है।temp_cubes := []खाली सूची बनाएं।iको 1 सेceil(n^(1/3))तक के लिए:cube = i³cubeString := str(cube)cubeStringकोtemp_cubesके अंत में जोड़ें।
temp_cubesलौटाएं।solve()फ़ंक्शन परिभाषित करें जोnum,temp_cubesलेता है।temp_cubesको उल्टा करें।totalCubes := len(temp_cubes)iको 0 सेtotalCubes - 1तक के लिए:temp := temp_cubes[i]digitsInCube := len(temp)index := 0digitsInNumber := len(num)jको 0 सेdigitsInNumber - 1तक के लिए:- यदि
num[j] == temp[index], तोindex := index + 1 - यदि
digitsInCube == index, तोtempलौटाएं।
- यदि
- "Not Possible" लौटाएं।
- मुख्य विधि से:
temp_cubes := preProcess(n)num := str(n)ans := solve(num, temp_cubes)ansलौटाएं।
उदाहरण
बेहतर समझ के लिए निम्न कार्यान्वयन देखें:
import math
def preProcess(n):
temp_cubes = []
for i in range(1, math.ceil(n ** (1. / 3.))):
cube = i ** 3
cubeString = str(cube)
temp_cubes.append(cubeString)
return temp_cubes
def solve(num, temp_cubes):
temp_cubes = temp_cubes[::-1]
totalCubes = len(temp_cubes)
for i in range(totalCubes):
temp = temp_cubes[i]
digitsInCube = len(temp)
index = 0
digitsInNumber = len(num)
for j in range(digitsInNumber):
if num[j] == temp[index]:
index += 1
if digitsInCube == index:
return temp
return "Not Possible"
def getLargestCube(n):
temp_cubes = preProcess(n)
num = str(n)
ans = solve(num, temp_cubes)
return ans
n = 806
print(getLargestCube(n))
इनपुट
806
आउटपुट
8