Imports System
Module ProductExceptSelfModule
'
' Computes product of array except self.
' nums = input array
' size = number of elements
' returns a new array containing the result
'
Function ProductExceptSelf(nums As Integer(), size As Integer) As Integer()
Dim answer(size - 1) As Integer ' allocate output array
Dim prefix As Integer = 1
' ---- Prefix products ----
' answer(i) gets product of all elements before i
For i As Integer = 0 To size - 1
answer(i) = prefix ' store prefix product
prefix *= nums(i) ' update prefix
' Example for nums = {5,2,3,4}:
' prefix values: 1, 5, 10, 30
Next
' ---- Suffix products ----
' Multiply each answer(i) by product of all elements after i
Dim suffix As Integer = 1
For i As Integer = size - 1 To 0 Step -1
answer(i) *= suffix ' combine prefix * suffix
suffix *= nums(i) ' update suffix
' suffix values: 1, 4, 12, 24, 120
' final answer: 24, 60, 40, 30
' 24 (24*1) 60 (12*5) 40 (10*4) 30 (30*1)
Next
Return answer
End Function
Sub Main()
Dim arr() As Integer = {5, 2, 3, 4}
Dim size As Integer = arr.Length
Dim result() As Integer = ProductExceptSelf(arr, size)
Console.Write("Result: ")
For Each x In result
Console.Write(x & " ")
Next
End Sub
End Module
' run:
'
' Result: 24 60 40 30
'