From 092cc1614671caf5b5242b3bf42664831561bb95 Mon Sep 17 00:00:00 2001 From: Aadhavan Srinivasan Date: Tue, 14 Feb 2023 23:06:46 -0600 Subject: [PATCH] Added 'Even Fibonacci' solution --- evenFibonacci/README.md | 3 +++ evenFibonacci/main.c | 8 ++++++++ evenFibonacci/main.s | 35 +++++++++++++++++++++++++++++++++++ 3 files changed, 46 insertions(+) create mode 100644 evenFibonacci/README.md create mode 100644 evenFibonacci/main.c create mode 100644 evenFibonacci/main.s diff --git a/evenFibonacci/README.md b/evenFibonacci/README.md new file mode 100644 index 0000000..9d78765 --- /dev/null +++ b/evenFibonacci/README.md @@ -0,0 +1,3 @@ +## Multiples of 3 or 5 + +This directory contains my solution to the ['Even Fibonacci numbers' problem](https://projecteuler.net/problem=2). diff --git a/evenFibonacci/main.c b/evenFibonacci/main.c new file mode 100644 index 0000000..ed92874 --- /dev/null +++ b/evenFibonacci/main.c @@ -0,0 +1,8 @@ +#include + +int evenFib(); + +void main() { + printf("%d\n",evenFib()); + return; +} diff --git a/evenFibonacci/main.s b/evenFibonacci/main.s new file mode 100644 index 0000000..b3168b8 --- /dev/null +++ b/evenFibonacci/main.s @@ -0,0 +1,35 @@ +.global evenFib + +.section .text +evenFib: +init: + PUSH {R4} @The ARM calling convention only allows callee functions to use R0-R3. Since I need R4 as well, I am going to push R4 onto the stack, and pop it off when I am done using it. + MOV R0,#0 @Return value - where all the addition is going to happen to + LDR R4,=#4000000 @ARM doesn't allow you to 'MOV' constants greater than 8 bits. To get around that, we use the LDR instruction, which lets the assembler place the value in memory, and then load it from there. + MOV R1,#1 @Main fibonacci number + MOV R2,#0 @Used to hold temporary values when incrementing the main fibonacci number + MOV R3,#0 @Previous fibonacci number - This will be 0 at the start +loop: + +incr: + MOV R2,R1 @Store the current fibonacci number in R2 + ADD R1,R1,R3 @Add the previous fibonacci number with the current one + MOV R3,R2 @Move R2 (the 'old current' fibonacci number) into R3 +checkbnd: + CMP R1,R4 @Check if R1 is greater than the upper bound for fibonacci numbers + BGE return @If it is, then we return + +checkparity: @Parity - The fact of being even or odd. + TST R1,#0x1 @Equivalent of an ANDS operation, but the result is discarded. In this case, we are checking if R1's parity by checking the last bit, which would be set to 0 if it is even, and 1 if it is odd. + BNE loop @If R1 is odd, don't do the addition. Instead, go back to the loop, where we move on to the next fibonacci number. + + +isEven: @The program goes here if R1 is even + ADD R0,R0,R1 @Add the fibonacci number to R0 + B loop + +return: + POP {R4} @Pop the R4 that we pushed onto the stack earlier + BX lr + +.section .data