You would pick some number a, run the code, and see if you can find a pattern. There will be an obvious pattern. Then you think how you can use that pattern to find long ranges of numbers i where r ends up being 1, and long ranges where r does not end up being 1.
When you've done that, all you do is add up the number of values in those ranges of values i that end up being 1.
The best way unless you are a super genius (in which case you wouldn't be asking here) is to play around with the code, figure out its behaviour, and think about ways to take shortcuts.