2. Find the sum of all the even-valued terms in the Fibonacci sequence which do not exceed four million.
At this point I see that I'm going to need to make some reusable classes for generating numbers as I see Fibonacci and Primes mentioned several times in the first couple of questions.
Here's my generator class.
vb.net Code:
Public MustInherit Class Yielder(Of T)
Implements IEnumerable(Of T)
Implements IEnumerator(Of T)
Private _current As T
Public Sub New()
End Sub
Protected MustOverride Function [Yield]() As T
Public Function GetEnumerator() As System.Collections.Generic.IEnumerator(Of T) Implements System.Collections.Generic.IEnumerable(Of T).GetEnumerator
Return Me
End Function
Public Function GetEnumerator1() As System.Collections.IEnumerator Implements System.Collections.IEnumerable.GetEnumerator
Return Me
End Function
Public ReadOnly Property Current As T Implements System.Collections.Generic.IEnumerator(Of T).Current
Get
Return _current
End Get
End Property
Public ReadOnly Property Current1 As Object Implements System.Collections.IEnumerator.Current
Get
Return _current
End Get
End Property
Public Function MoveNext() As Boolean Implements System.Collections.IEnumerator.MoveNext
_current = [Yield]()
Return True
End Function
Public Sub Reset() Implements System.Collections.IEnumerator.Reset
Throw New NotImplementedException()
End Sub
#Region "IDisposable Support"
Private disposedValue As Boolean ' To detect redundant calls
' IDisposable
Protected Overridable Sub Dispose(disposing As Boolean)
If Not Me.disposedValue Then
If disposing Then
End If
End If
Me.disposedValue = True
End Sub
Public Sub Dispose() Implements IDisposable.Dispose
Dispose(True)
GC.SuppressFinalize(Me)
End Sub
#End Region
End Class
My Fibonacci generator class
vb.net Code:
Public Class Fibonacci
Inherits Yielder(Of Long)
Private a = 0
Private b = 1
Protected Overrides Function [Yield]() As Long
b = a + b
a = b - a
Return b
End Function
End Class
vb.net Code:
Private Function Problem2() As Integer
Return New Fibonacci() _
.Where(Function(x) x Mod 2 = 0) _
.TakeWhile(Function(p) p < 4000000) _
.Aggregate(Function(sum, x) sum + x)
End Function