2

I'm having trouble coding in ARM Assembly, I have to code something in order to say if r0 is divisible by r1, so I was going to code the modulo to say if r0 % r1 == 0 but maybe there's a better way (performing speaking) to what I want?

I found this subject but it's not really helping me out since my compiler (if it's a compiler ^^) which is arm-eabi-gcc tells me selected processor does not support ARM mode 'udiv' and 'mls'

Anyways as I just said I'd prefer to code it myself because teachers have been telling us that mod and div have heavy cost, so maybe there's a better way for my case :D

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
Axel Carré
  • 303
  • 1
  • 5
  • 2
    You could use the algorithm of Euclid to see if gcd(r0,r1) == r1. – fuz Mar 15 '18 at 12:00
  • And which processor are you programming for exactly? – fuz Mar 15 '18 at 12:00
  • [Divisibility testing is cheap when the modulus is known at compile time](https://stackoverflow.com/questions/6896533/fast-divisibility-tests-by-2-3-4-5-16/49264279#49264279); only a multiply and compare. It's not when you need it to work with any value in a register. Even though hardware `div` / `udiv` is slow, it's the best solution. If your CPU doesn't have division in HW, then you're going to need some kind of loop. – Peter Cordes Mar 15 '18 at 12:05
  • 1
    @fuz's suggestion of a GCD is good for a divisibility test where you don't actually need to know the quotient or modulo. Wikipedia says that Euclid's algorithm isn't the fastest in practice. https://en.wikipedia.org/wiki/Binary_GCD_algorithm is faster on real CPUs, although both algorithms are O(n^2) worst-case time, where `n` is the number of bits in the larger number. – Peter Cordes Mar 15 '18 at 12:22
  • 2
    A good way to implement Euclid's algorithm is the [algorithm of Stein](https://en.wikipedia.org/wiki/Binary_GCD_algorithm) by the way. It should be a lot of fun to implement it on ARM, you can find my own x86 implementation [here](https://gist.github.com/fuzxxl/3b882a2f8ed0adb1a13f10a4d9f1ce0b) for reference. – fuz Mar 15 '18 at 12:31
  • Alright thanks everyone I was looking for :) – Axel Carré Mar 15 '18 at 12:31

0 Answers0