ray_milan
ray_milan

Reputation: 37

Why the Code/Logic is working differently for different ranges?

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.

Upvotes: 0

Views: 44

Answers (1)

Prasad Darshana
Prasad Darshana

Reputation: 316

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 ")

Upvotes: 1

Related Questions