Microsoft Small Basic

Program Listing:
Embed this in your website

' Euler Problem 1 - Generalization

'With this method are carried out all and only the iterations needed

' maxNumber : Maximum value in the sequence of summands
' sum : Summation
' i : Counter
' a : in Euler Problem 1 is 3
' b : in Euler Problem 1 is 5
' c : a temporary variable for the swap
' i3 : always i*a, that is a multiple of a
' i5 : always i*b, that is a multiple of b



TextWindow.WriteLine("Maximum value in the sequence of summands (1000 for Euler P1 ): ")
maxNumber=TextWindow.ReadNumber()
If(maxNumber<=0)Then
  maxNumber=1000 ' if maxNumber si not valid I use a default value
EndIf

TextWindow.WriteLine("The summands are mulptiple of (3 in Euler P1 )...: ")
a=TextWindow.ReadNumber()
If(a<=0)Then
  a=3  'if a si not valid I use a default value
EndIf

TextWindow.WriteLine("...or multiple of (5 in Euler P1 ): ")
c=TextWindow.ReadNumber()
If(c<=0)Then
  c=5   'if b si not valid I use a default value
EndIf

'It's necessary that a
If(c>a)Then
  b=c
Else
  b=a
  a=c
EndIf

' Cycle Initialization.
' If we had a repeat-until or do-while cycle , we had been able to write
' more elegant code
sum=0  ' Summation start by 0
i=1    ' Every good counter start with 1
i5=i*b ' This will contain the 'b' times table... one element at time
i3=i*a ' This will contain the 'a' times table... one element at time

'While the summands are lower than maxNumber (1000)...
'I do not check i5 because a
'when i3 will be greater than 1000, i5 will be greater than 1000 too
While(i3<maxNumber)
  sum=sum+i3    ' i3 is always a good summand
  'If the remainder(i5,a) is 0 then i5 is divisible by a then i have already taken it as i3 value
  'in addition i5 reaches maxNumber before i3 because a
  If(i5<maxNumber And (Math.Remainder(i5,a)<>0))Then
    sum=sum+i5  ' i5 is a good summand
  EndIf
  i=i+1  ' Counter Increment
  i5=i*b ' Next element in 'b' times table
  i3=i*a ' Next element in 'a' times table
EndWhile

' Show the result
TextWindow.WriteLine("")
TextWindow.WriteLine("*************** Problem 1 ***************")
TextWindow.WriteLine("If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.")
TextWindow.WriteLine("Find the sum of all the multiples of "+a+" or "+b+" below "+maxNumber+".")
TextWindow.WriteLine("")
TextWindow.WriteLine("The solution is "+sum+" obtained with "+i+" iterations")
Copyright (c) Microsoft Corporation. All rights reserved.