Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBA Odd Numbers/Mod

Tags:

vba

mod

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.

like image 301
K. L. Avatar asked Dec 14 '22 00:12

K. L.


2 Answers

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:

enter image description here

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.

like image 131
John Coleman Avatar answered Jan 04 '23 02:01

John Coleman


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
like image 45
Dan Donoghue Avatar answered Jan 04 '23 02:01

Dan Donoghue