I'm looking for some help with my VBA script. I'm stuck on trying to figure out how to use the mod function.
This is what I've done so far:
Function AddOddNumbersWithMod(nr)
Dim i, sum
sum = 0
For i = (IF 1 MOD 2 = 0) to nr step 1
sum = sum + i <-- (calculate all the odd numbers before nr)
Next i
End Function
Any advice would be greatly appreciated.
For completeness sake, here is a loop-free version:
Function SumOfOdds(n As Long) As Long
'returns sum 1 + 3 + 5 + ... of all odd numbers <= n
SumOfOdds = Int((n + 1) / 2) ^ 2
End Function
Based on this picture:
The L-like shapes contain successive odd numbers and nicely fit together to form perfect squares. This nice pattern was well-known to the ancient Greeks.
You want the result of i Mod 2 to be 1, it shows the remainder and if you are using 2 as your divisor you want a remainder of 1 to show an odd number. For example 7 mod 2 = 1, this is because 7 divided by 2 equals 3 with a remainder of 1, it's that remainder that we are interested in.:
Function AddOddNumbersWithMod(nr)
Dim i As Double, MySum As Double
For i = 0 To nr
If i Mod 2 = 1 Then MySum = MySum + i ' <-- (calculate all the odd numbers before nr)
Next i
AddOddNumbersWithMod = MySum
End Function
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With