Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

having trouble making a brute force program that finds out if a number is equal to itself in reverse

basically the title, I have a program that I’m trying to write to see if 2 3-digit number multiplied by each other equal a palindromic number, the problem I am having with the code is that when I run it it doesn’t display anything whatsoever

def Rev(Number):    
    Reverse = 0    
    while(Number > 0):    
        Reminder = Number %10    
        Reverse = (Reverse *10) + Reminder    
        Number = Number //10    


num1 = 100
num2 = 100
mult = 0
reverse = Rev(mult)

x = 0

while x < 1:
    while num1 < 1000:
        while num2 < 1000:
            mult = num1 * num2
            reverse = Rev(mult)
            if reverse == mult:
                print(mult)
            num2 = num2 + 1
        num1 = num1 + 1
    x = x + 1

I also tried adding a print(Reverse) to the end of the Rev function so it displays the output after, but it gives a bunch of zeros and other random numbers

I’m still a beginner in python so I may just be dumb but I appreciate any help given

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You have a couple of issues. The first is that Rev doesn’t return a value (so by default it returns None), and so reverse will never be equal to a number. The second is that you need to re-initialise num2 for every num1 loop. Finally the x variable is not doing anything, so you can just remove the outer while loop. This code does what you want:

def Rev(Number):    
    Reverse = 0    
    while(Number > 0):    
        Reminder = Number %10    
        Reverse = (Reverse *10) + Reminder    
        Number = Number //10  
    return Reverse

num1 = 100

while num1 < 1000:
    num2 = 100
    while num2 < 1000:
        mult = num1 * num2
        reverse = Rev(mult)
        if reverse == mult:
            print(mult)
        num2 = num2 + 1
    num1 = num1 + 1

Output:

10201
11211
12221
13231
14241
15251
...
282282
119911
906609
514415
580085

Note you may want to store results into a list/dictionary to make it easier to display them in a prettier format.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading