VBA Odd Numbers / Mod

I need help with a VBA script. I am stuck trying to figure out how to use the mod feature.

This is what I have 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 is appreciated.

+4
source share
3 answers

For completeness, there is no version without a loop:

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 image:

enter image description here

L-shaped figures contain consecutive odd numbers and combine perfectly with each other to form perfect squares. This beautiful drawing was well known to the ancient Greeks.

+7
source
Function AddOddNumbersWithMod(nr)
    Dim i As Long, sum As Long
    sum = 0
    For i = 1 To nr - 1 Step 1
        If (i Mod 2 <> 0) Then
            sum = sum + i  ' <-- (calculate all the odd numbers before nr)
        End If
    Next i

    AddOddNumbersWithMod = sum
End Function

To add odd numbers without Mod, you can use Step 2 to skip even numbers starting at 1.

Function AddOddNumbersWithoutMod(nr)
    Dim i As Long, sum As Long
    sum = 0
    For i = 1 To nr - 1 Step 2
        sum = sum + i  ' <-- (calculate all the odd numbers before nr)
    Next i

    AddOddNumbersWithoutMod = sum
End Function
+2
source

, Mod 2 1, , 2 , , 1 . , 7 mod 2 = 1, , 7, 2, 3 1, , .:

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
+2

Source: https://habr.com/ru/post/1670684/


All Articles