Home > Software design >  Why the Code/Logic is working differently for different ranges?
Why the Code/Logic is working differently for different ranges?

Time:09-28

I wrote the code for problem 4 of Project Euler-- it works perfectly for the range (10,100)-- case1--

for i in range(10,100):
    for j in range(10,100):
        a = i*j
        b = str(a)
        d = str(a)[::-1]
        if b == d:
            c = b
            p1 = i
            p2 = j
print(f"{c} is palindrome ")

but for range (100,1000) case2---

for i in range(100,1000):
    for j in range(100,1000):       
        a = i*j
        b = str(a)
        d = str(a)[::-1]
        if b == d:
            c = b
            p1 = i
            p2 = j    
print(f"{c} is palindrome ")

the output is wrong WHY?? Why the code works differently ?? For case1 it gives the correct output. But as the range changes it provides wrong output.

CodePudding user response:

In your logic, if any palindrome is found it automatically assigns to c without checking it is greater than to c. for example when i=993 and j =913 then c= 906609 but this value replace by 580085 when i =995 and j = 583. So you cannot get expected output.

first, try, I provided the sample code below. Look at only if you didn't get the idea.

c=0
for i in range(100,1000):
    for j in range(100,1000):       
        a = i*j
        b = str(a)
        d = str(a)[::-1]
        if b == d:

            if a>c:
                c=a

            p1 = i
            p2 = j    
print(f"{c} is palindrome ")
  • Related