ProjectEuler.net Problem 4 – ARM Assembly


Improve your writing skills in 5 minutes a day with the Daily Writing Tips email newsletter.

I am starting to play around with ARM Assembly, and to practice I decided to solve some problems on Project Euler with it. Below you’ll find problem 4 and its solution. Keep in mind that the code is not that efficient right now, as it’s taking about 2 minutes to run, but it does solve the problem correctly.

The problem:

A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 99.

Find the largest palindrome made from the product of two 3-digit numbers.

The solution:

.extern printf
.global main

main:
        push {ip,lr}

        mov r4, #100
        mov r9, #0
        loop1:
                mov r5, #100
                loop2:
                        mul r1, r4, r5
                        bl isPalindrome
                        cmp r0, #1
                        bne continue
                                cmp r1, r9
                                blt continue
                                mov r9, r1
                        continue:
                        add r5, r5, #1
                        cmp r5, #1000
                        blt loop2
                add r4, r4, #1
                cmp r4, #1000
                blt loop1

        ldr r0, =printf1
        mov r1, r9
        bl printf

        mov r0, #0
        pop {ip,pc}

        isPalindrome:
                push {lr}
                mov r6, #0
                mov r7, #10
                mov r2, r1
                process:
                        bl findModulus

                        mov r12, r6
                        mul r6, r12, r7
                        add r6, r6, r3

                        bl divR2

                        cmp r2, #0
                        bgt process

                pop {lr}

                cmp r1, r6
                beq equal
                mov r0, #0
                b finish
                equal:
                        mov r0, #1
                finish:
                        bx lr

        findModulus:
                mov r3, r2
                start:
                        subs r3, r3, #10
                        bpl start
                add r3, r3, #10
                bx lr

        divR2:
                mov r8, #0

                division:
                        cmp r2, #10
                        blt finishDiv
                        sub r2, r2, #10
                        add r8, r8, #1
                        b division
                finishDiv:
                mov r2, r8
                bx lr

        printf1: .asciz "largest palindrome -> %dn"

Leave a Reply

Your email address will not be published. Required fields are marked *