PDA

View Full Version : Programming Puzzle 1 - Simple Loop


ABC123

Tom Cone Jr
06-02-2011, 08:19 PM
If you've been thinking that this summer might be a good time to learn a little xbasic, I have a treat in store for you.

I'm planning to post a series of programming puzzles for you to work on. Puzzles that must be worked out using xbasic.

Hopefully, these puzzles will give us a springboard from which we can discuss, teach, learn, and benefit from each other's experience.

In any event, here's my first offering.

The solution should be presented in the form of an xbasic script. The script should be posted here, or attached to a reply here. You should expect comments, questions, and even corrections. The object is not to "show off" but to provide a safe, non-judgmental area, where people who may be curious about programming, especially, programming in xbasic, can play, have fun, and learn. I rather suspect we'll see more than one way to solve these things. Alpha Five is nothing if not flexible, right?

Hope you like it.

-- tom

CALocklin
06-02-2011, 09:25 PM
OK, here's a down and dirty solution: (I just hope I got the right answer!)

OPTION strict
'Variables should not be "one word" or "one letter". Not because they won't
'work but because they can make debugging harder in long scripts.
'This is an "abbreviated two word" variable - two words to help make it
'unique for search purposes and abbreviated to make it faster to type.
'even_sum ==> esum.
DIM esum as N
'A single letter preceeded by "q" is easier to find in a search than, in this
'case, just the letter "e". The letter "e" is used 18 times but "qe" only 3.
DIM qe as N
'Set initial value to 0.
esum = 0
'Many people forget that a FOR...NEXT statement can also use a STEP command.
FOR qe = 102 to 302 step 2
esum = esum + qe
NEXT
DIM msg as C
'Although it's possible to use ui_msg_box( "TOTAL", "" + esum ) and let A5 do the
'conversion from number to text, it's valuable to know that it's actually faster
'if you explicitly specify the conversion. The extra time isn't noticeable in this
'case but it can be noticeable when a calculation is being done inside a long loop.
msg = "The sum of the even numbers between 101 and 302 is: " + ltrim( str( esum ) )
ui_msg_box( "TOTAL", msg, ui_information_symbol )
By the way, "Option Strict" requires that all variables be DIMmed. While it does have its advantages, I personally find it too annoying and virtually never use it. But that does require some care when naming variables to make sure you don't accidentally try to use a "local" variable that is already defined as global or shared.

BigBoss1
06-02-2011, 11:03 PM
Hi
Just a small addition to CALockin's answer to include the iterations in the loop.

DaveM
06-02-2011, 11:49 PM
David and Cal,

If you use the 101 instead of the 102, your answer is actually less. which is correct? Tom said 101-302.

CALocklin
06-03-2011, 01:17 AM
Dave, I'm happy to say you don't read any better than I do!

I completely missed the part where Tom said, "and the number of times your code iterated through your loop."

You missed the part where he said, "sums the even numbered values". 101 wasn't even last time I checked.

Tom Cone Jr
06-03-2011, 06:16 AM
Yes, grasshoppers. Understanding the question is the key to enlightenment. :grin:

For the beginners who may be lurking nearby, would anyone like to explain how the "For ... Next" loop does it's magic?

So far no one has attempted a solution using a "While ... End While" loop. Any takers?

Mbuso
06-03-2011, 07:02 AM
Heres a different approach...

will work with any two numbers from 0 to ... [tested with 1000000]

enjoy :-)

Stan Mathews
06-03-2011, 09:56 AM
A while loop version. Some lesser used functions and methods employed.


option strict
'If you place the OPTION STRICT command at the top of a script then you must declare variables explicitly using the DIM command.
dim entries_to_use as C = ""
dim qx as N = 101
dim loops as N = 0
'Dimming all variables in one place can make them easier to locate
TRACE.CLEAR() 'Clear the Trace window before writing text to it.
WHILE qx < 303
IF mod(qx,2) = 0 'checks for even number
entries_to_use = entries_to_use+alltrim(str(qx))+crlf() 'builds crlf() delimited string
traceln("Even number "+alltrim(str(qx))+" current loop value "+alltrim(str(loops))) 'writes the number and current loop to the trace window
END IF
qx = qx + 1 'increments possible values to be summed variable
loops = increment_value(loops) 'increments loop variable
END WHILE

qx = *total(entries_to_use) 'The *TOTAL() function totals a list of numeric entries.
'Note that there is nothing illegal about re-using a numeric variable for a second purpose
traceln("Sum "+alltrim(str(qx))+" total loops "+alltrim(str(loops)))
ui_msg_box("Note","Activate the Error tab of the next window to appear."+crlf()+"to see the sum of values and loop total.")
A5_TOGGLE_TRACE_WINDOW() 'The A5_TOGGLE_TRACE_WINDOW() function opens the Trace window if it is closed, and closes it if it is open.

Took some liberties with "and then display the answer in a message box....".

Al Buchholz
06-03-2011, 10:23 AM
Took some liberties with "and then display the answer in a message box....".

Your shore liberty is canceled - again :rofl:

Stan Mathews
06-03-2011, 10:38 AM
Another take using xdialog to display the results.


option strict
'If you place the OPTION STRICT command at the top of a script then you must declare variables explicitly using the DIM command.
dim entries_to_use as C = ""
dim qx as N = 101
dim loops as N = 0
DIM SHARED varC_result as C
dim ok_button_label as C = "&OK"
'Dimming all variables in one place can make them easier to locate
FOR qx = if(mod(qx,2)=0,qx,qx+1) TO 302 step 2 'computed starting loop value, optional step parameter
entries_to_use = entries_to_use+alltrim(str(qx))+crlf()
loops = increment_value(loops)
NEXT qx
qx = *total(entries_to_use) 'The *TOTAL() function totals a list of numeric entries.
'xdialog follows to display values, The R directive makes the text in a Text Box read-only.
varC_result = ui_dlg_box("Alpha Five",<<%dlg%
{region}
Loops:| [%r%.40loops];
Sum of Values:| [%r%.40qx];
{endregion};
{line=1,0};
{region}
<*15=ok_button_label!OK>
{endregion};
%dlg%)

GGandhi
06-03-2011, 11:25 AM
puzzle conditions:
1> use option strict
2> add up even numbers between 101 and 302 both inclusive
3> show the number of iterations and the result in a message box
4> include comments.
while i am not certainly an expert this is my attempt...


option strict
'dim all variables
'x iteration variable, j number palce holder for start and end
'sumx total of even nunbers
'msg
dim x as n=0
dim j as n
dim sumx as n=0
dim msg as c=""
for j=101 to 302
x=x+1
if mod(j,2)=0
sumx=sumx+j
end if
next
msg=("Total iterations: "+x+" Total of the even numbers: "+sumx)
ui_msg_box("Total Iterations",x)
ui_msg_box("Total of the even numbers",sumx)
ui_msg_box("Puzzle",msg)

Tom Cone Jr
06-03-2011, 12:00 PM
Govindan, that's very good. You've used the loop correctly. Notice several things:

a) the message board reformatted your code, forcing every line to be left justified. You can overcome this and preserve the formatting in your script if you use the "advanced" message board editor (choose "Go Advanced" button). Then select the text to be "preserved" and apply "CODE" tags to it. If this isn't clear let us know.

b) In these lines:

msg=("Total iterations: "+x+" Total of the even numbers: "+sumx)
ui_msg_box("Total Iterations",x)
ui_msg_box("Total of the even numbers",sumx) you're concatenating character strings with numeric values. To do this Alpha must convert your numeric values to character strings for you. While Alpha tries hard to do this "implied" data type conversion when it's needed, it does not always succeed. A better practice is to explicitly convert your numeric data to character strings before doing the concatenation. Check Cal Locklin's sample code in this thread (above).

c) Also, notice that once the first "even" number is encountered, you could optimize the code by stepping through the number range two numbers at a time. Bouncing from even to even so to speak. This would cut the number of trips through loop in half if you see what I mean.

Good work.

-- tom

CALocklin
06-03-2011, 04:50 PM
...
'Dimming all variables in one place can make them easier to locate
...

And alphabetizing a long list makes it easier also. I do this often enough that I've included a "sort clipboard" routine in my AIMS Grab Bag. (At least I think it's there. I know it's in my personal version.) The code is really simple - just one line - and could be added to a custom "Sort Clipboard" button on your Code Editor toolbar:

clipboard.set_data( sortsubstr( clipboard.get_data(), crlf() ) )

To use it for sorting a group of lines in your Code Editor, just highlight the lines, press Ctrl-C to copy them, click the custom button to sort them, and press Ctrl-V to replace the already selected "old" list with the sorted string. (Ctrl-V is the shortcut key for "Paste".)

I also use this in other places. For example, I've sometimes created a crlf list for the user to select from, added and/or deleted from it, and then want to sort the list to make it easier for the user to work with.

GGandhi
06-03-2011, 09:13 PM
Govindan, that's very good. You've used the loop correctly. Notice several things:

a) the message board reformatted your code, forcing every line to be left justified. You can overcome this and preserve the formatting in your script if you use the "advanced" message board editor (choose "Go Advanced" button). Then select the text to be "preserved" and apply "CODE" tags to it. If this isn't clear let us know.

b) In these lines:

msg=("Total iterations: "+x+" Total of the even numbers: "+sumx)
ui_msg_box("Total Iterations",x)
ui_msg_box("Total of the even numbers",sumx) you're concatenating character strings with numeric values. To do this Alpha must convert your numeric values to character strings for you. While Alpha tries hard to do this "implied" data type conversion when it's needed, it does not always succeed. A better practice is to explicitly convert your numeric data to character strings before doing the concatenation. Check Cal Locklin's sample code in this thread (above).

c) Also, notice that once the first "even" number is encountered, you could optimize the code by stepping through the number range two numbers at a time. Bouncing from even to even so to speak. This would cut the number of trips through loop in half if you see what I mean.

Good work.

-- tom

Thank you, Much appreciated.

gandhi

pmanandhar
06-06-2011, 10:05 AM
This is the basic, simplest and best problem for anyone learning to program. I saw some of the simplest code and a little challenging ones. I was wondering if anyone even thought to solve this without using a loop?? Anyone?? I am sorry that I'm not following the question to solve the answer but my point is to view things little differently.

Check this out:
Below is the code to add even/odd numbers between n1 and n2 without using any loops. I'm sorry again that I'm violating the rules of the question and not following instructions. But here is something I got.. I created a formula to add odd and even numbers.


dim n1 as n
dim n2 as n
dim x1 as n
dim x2 as n
dim add_even as n = 0
dim add_odd as n = 0
dim msg as c=""
n1 = 101
n2 = 302
x1 = n1
x2 = n2
if (mod(n1,2)=0)
n1=n1-1
end if
if (mod(n2,2)=1)
n2=n2-1
end if
if (mod(x1,2)=0)
x1=x1+1
end if
if (mod(x2,2)=1)
x2=x2+1
end if
add_even=((n2^2)-(n1^2)+(n2*2)+1)/4
add_odd =((x2^2)-(x1^2)+(x1*2)-1)/4
?add_even+"<br/>"
?add_odd+""

Tom Cone Jr
06-06-2011, 10:32 AM
Thinking outside the box, are we, now?

Pratik, your solution gets the correct result. However, our fearless scorekeeper, "Ignatious A. Pickypicky", has deducted points for (a) the absence of explanatory comments; and (b) the failure to display the computed results in a message box. Care to try again? Maybe you'll catch Pickypicky in a better mood!

pmanandhar
06-06-2011, 10:52 AM
hi tom,
I wasn't really worried about the points but now you said it so I made some changes with comments, loop and message box. So, do I get the bonus point for the least iterations.

option strict
'dim all variables
'n1 = starting value , n2 = ending value (both inclusive)
dim n1 as n = 0
dim n2 as n = 0
dim x1 as n = 0
dim x2 as n = 0
dim i as n = 0
dim add_even as n = 0 ' to add even numbers
dim add_odd as n = 0 ' to add odd number (optional)
dim msg as c=""
n1 = 101 ' start value to add
n2 = 302 ' end value to stop adding
x1 = n1
x2 = n2
i = 1
if (mod(n1,2)=0) ' check if even
n1=n1-1 'subtract one because by formula works with starting value as odd and ending as even
end if
if (mod(n2,2)=1) ' similiar to above reason
n2=n2-1
end if
if (mod(x1,2)=0)
x1=x1+1
end if
if (mod(x2,2)=1)
x2=x2+1
end if
for i = 1 to 1
add_even=((n2^2)-(n1^2)+(n2*2)+1)/4 'formula to add even values between n1 and n2
add_odd =((x2^2)-(x1^2)+(x1*2)-1)/4 'formula to add odd values between n1 and n2
next
ui_msg_box("Total Iterations",i)
ui_msg_box("Total of the even numbers",add_even)
ui_msg_box("Total of the odd numbers",add_odd)

Tom Cone Jr
06-06-2011, 11:10 AM
So, do I get the bonus point for the least iterations?

Sorry, no. By stepping out of the bounds created for the exercse you've earned the careful attention of our venerable scorekeeper, Prof. Pickypicky. He will be keeping a sharp eye on your future puzzle submittals!

ps. I'd be tempted to ask him to reconsider if your script furnished a "proof" for the even number formula you employed.

-- tom

pmanandhar
06-06-2011, 11:23 AM
hey tom,
I am new to this forum and don't know what you and your "Prof. Pickypicky" is talking about. Maybe I'm little careless that even in my classes I rarely got an A (instead A- or B+) even though I get the job done. I don't know what proof are you asking and i don't know how to proof ?? I am good in math so I just took some time and came up with this formula. Now if you are interested as how I came up with this formula then I can explain but still its little complicated to explain. you can try using different values in n1 and n2 several times. That works so is that considered "proof"??

Tom Cone Jr
06-06-2011, 11:43 AM
Pratik,

I was mostly pulling your leg. Trying to be facetious. No mathematical proof is necessary. Thanks for contributing to this thread. I look forward to your answers on other puzzles in the future. -- tom

CALocklin
06-06-2011, 04:13 PM
Nice job Pratik! When I posted my original solution I was pretty sure there had to be some way to do it without any iterations but didn't have the time to work it out. And seeing your solution - probably not the ability either.

Mbuso
06-06-2011, 04:58 PM
upon a realisation that my input attracts no response other than anonymous respondents through email and private messages. No harm in posting another version, yet in attempt to contribution in a speedier progress for a would be alpha fellow.

regards,

Tom Cone Jr
06-06-2011, 05:33 PM
Mbuso,

Very nice! Thinking outside the box. Your solution does not use a loop, but is ingenious nevertheless. In your algorithm you adjust the end points of the number range, then compute both the number of "even" terms and the avg over the entire range. Multiplying them together you get the sum. Very clever, grasshopper! Prof. Pickypicky will be watching you closely, too!

Mbuso
06-06-2011, 11:55 PM
...Very clever, grasshopper!...

*blushing* ...

with a slight modification the same can be applied to calculate sum of equal contributions made in to investment or loan repayment. Which indeed, can also be done the snaky route (loop:-)

pmanandhar
06-07-2011, 08:21 AM
CALocklin - Its not that difficult and you definitely have the ability (maybe not time). It took me a while to figure out the logic and formula. I saw Mbuso's logic too and its way easier than the way I was doing. His logic was to get the start and end numbers to be even. Then, get the average (easy to calculate), and times no. of even numbers which is (N+1)/2.. That's it.. brilliant..
I was also thinking similiar but the question wanted to calcuate from 101 -302. So wanted the input to be starting -odd and ending- even numbers. I did it for adding odd numbers which made little complications.

Mbuso
06-07-2011, 09:37 AM
thanx pmanandhar.
interesting to read your work since you have a taste for math, and background in cpp, as seen in flyPuzzle :-)

jeb richardson
08-03-2011, 11:45 AM
OPTION strict
dim sum as N
'defining sum variable as Number. Sum will be used to get the total sum of the even number through the range.
dim qx as N
'defining qx variable as Number. QX will be used as the loop.
dim lnum as N
'defining lnum variable as Number. Lnum will be used to get the total times the loop was done.
sum=0
lnum=0
FOR qx = 102 TO 302 step 2
'starting the loop. Stating loop is is going to be ran from 102 to 302. 'Step 2' defines the number to increase by after each loop.
sum=sum+qx
'equation that gets the value for each loop cycle(each QX) and eventually will add them together.
lnum=lnum+1
'equation that sets the first loop to 1. The second loop to 2. The third loop to 3, etc.
next
'goes to next part of loop(next QX).
message="The sum of the even numbers through the range 102-302 is: "+sum
message2="The number of times the code was iterated through the loop was: "+lnum
ui_msg_box("Jeb's Calculation",message +crlf()+message2)

Tom Cone Jr
08-03-2011, 03:08 PM
Jeb, good try. Prof. Ignatious Pickypicky has several comments for your elucidation (his word, not mine!) :grin:

1) The pound symbol on the "Next" line throws an error. It doesn't belong.

2) The message box fails to display because the variables "message" and "message2" haven't been declared,
and OPTION STRICT is on.

3) The professor's eyes aren't what they used to be. Consider formatting your scripts so they're easier
to read. (Example below to give you some ideas).

4) It's not necessary to comment every line. Some things will always be obvious when you come back to
the script years later. Others will not. The latter is what must be documented / commented.

5) It's customary to indent lines inside a code block / loop structure.


OPTION strict

'recommend DIMing all vars at the top
dim sum as N 'defining sum variable as Number. Sum will be used to get the
'total sum of the even number through the range.
dim qx as N 'defining qx variable as Number. QX will be used as the loop.
dim lnum as N 'defining lnum variable as Number. Lnum will be used to get the
'total times the loop was done.
dim qx as N 'loop counter (index)
dim message as C 'text string for message box
dim message2 as C 'ditto


sum=0 'giving the sum variable a value of zero.
lnum=0 'giving the lnum variable a value of zero.

for qx = 102 to 302 step 2 'starting the loop. Stating loop is is going to be
'ran from 102 to 302. 'Step 2' defines the number
'to increase by after each loop.

sum=sum+qx 'equation that gets the value for each loop cycle(each QX) and
'eventually will add them together.

lnum=lnum+1 'equation that sets the first loop to 1. The second loop to 2.
'The third loop to 3, etc.

next 'goes to next part of loop(next QX).

dim message as C
dim message2 as C

'assigning the total sum message for the pop up message.
message="The sum of the even numbers through the range 102-302 is: "+ltrim(str(sum))

'assigning the total lnum or total times the loop was done, for the pop up message.
message2="The number of times the code was iterated through the loop was: "+ltrim(str(lnum))

ui_msg_box("Jeb's Calculation",message +crlf()+message2) 'message box that gives
'the results of the calculation. LNUM and SUM.

The Mage
10-02-2011, 09:36 PM
OPTION strict

dim first as N 'Starting number
dim last as N 'Ending number
dim total as N 'For final total
dim count as N 'To count the number of times this code is run, but it won't be that important as you will see.

count = 0 'Starting counter at 0

first = 102 'Starting point
last = 302 'Ending point

total = ( ( first + last ) * ( last - first ) ) / 4
'By adding in the first and last numbers I am figuring out a standard number for the math
'and by subtracting the last and first from eachother, I am counting the total of the
'numbers between the first and last. Since I am adding in both first and last numbers,
'I only need to figure in half of those numbers, and since only even numbers are counted,
'I need only half of those numbers still. So I divide the total by 4.
'logically it should have divided the (last-first) before being multiplied, but the result is the same.

count = count + 1 'Adding to the counter

'Results:
ui_msg_box( " Total" , total ,UI_ATTENTION_SYMBOL )

'Number of times the formula had to be run:
ui_msg_box( "Times Run" , count , UI_ATTENTION_SYMBOL )

Admittedly I am cheating here by not using a loop.

Tom Reese
11-10-2011, 08:41 AM
As I am very new to xbasic my version to puzzle 1 is simple, but I believe it gets the job done.
Would appreciate any comments that may be needed or helpful.

Now to see if I can find Puzzle 2.

'Date Created: 09-Nov-2011 05:23:03 PM
'Last Updated: 10-Nov-2011 08:12:35 AM
'Created By : T. E. Reese
'Updated By : T. E. Reese
option strict

dim target_num as n = 0 'used to determine if number is even
dim i as n = 0
dim result as n = 0 'result adds the total of the even numbers
dim num_loops as n = 0 'counts the number of interations

for i = 302 to 101 step-2
num_loops = num_loops + 1
target_num = i
if mod(target_num,2)= 0 then
result=result+target_num
end if
next i

ui_msg_box("Program Puzzle One","The answeres are Sum = "+ alltrim(str(result))+" Loops = "+alltrim(str(num_loops)))

end

Tom Cone Jr
11-10-2011, 08:59 AM
Very nice, Thomas.

The message board left justifies your script. That makes it harder to read scripts because we lose the indents.

To preserve the indents prepare your reply using the "Go Advanced" button, and then encapsulate your code with CODE tags, like this:


option strict

dim target_num as n = 0 'used to determine if number is even
dim i as n = 0
dim result as n = 0 'result adds the total of the even numbers
dim num_loops as n = 0 'counts the number of interations

for i = 302 to 101 step-2
num_loops = num_loops + 1
target_num = i
if mod(target_num,2)= 0 then
result=result+target_num
end if
next i

ui_msg_box("Program Puzzle One","The answeres are Sum = "+ alltrim(str(result))+" Loops = "+alltrim(str(num_loops)))

end

The # button on the advanced editor toolbar will do this for you. Just select the text to be encapsulated, and click #.

Also, when you develop a solution to the next puzzle, I suggest you learn how to "export" your script as a text file, and then simply attach it to a reply here. If you use the script export tool in Alpha Five the text file will be specially formatted to work with Alpha's import tool. This makes it easier for us to study your code and run it on our machines. We just import your previously exported script. To get to the export (and import) tools, save your script to the Code page of the A5 control panel. Then right click the script name. Choose Export off the drop down list (context menu).

Welcome to the board!

G Gabriel
12-26-2011, 11:17 AM
Just came across this part of the message board. Not sure whose idea it is to have a section for "Puzzles"..but I think it's a pretty good idea..
On to the first puzzle..don't have time to scan over any others..nor to scan over the responses, but this puzzle, clearly, can be solved without any loops whatsoever, rather with one simple expression. But if I do that then I am in violation of the rules.
For those who might be interested, here is the expression:

vtotal=int((end-start)/2)+1+(int((end-start)/2)+1)*if(mod(start,2)=0,start-2,int(start/2)*2)+(int((end-start)/2)+1)^2
Where vtotal is the sum of all even values, start is the bottom value and end is the top value, all inclusive.

If I want to be de facto in compliance with the rules, I could be a slick, clever, irritating smart alec, which I do not want to be, but again, for those who might be interest, I will use a single loop that does nothing and I will have my lawyer sue and demand the ultimate prize arguing that I am in full compliance with the rules the way they were written and offered.
Here is the smart alec script:

option strict
dim start as n'this is the bottom value
dim end as n'this is the top value
dim i as n 'to be used as a counter in the loop
dim vtotal as n
start=101
end = 302
'Now we will use the same expression provided in the previous example and add a dummy loop
for i=1 to 1
vtotal=int((end-start)/2)+1+(int((end-start)/2)+1)*if(mod(start,2)=0,start-2,int(start/2)*2)+(int((end-start)/2)+1)^2
next
msgbox("The total sum is: "+vtotal+" and the script used 1 loop")


'The same could be done using while..end while loop

option strict
dim start as n'this is the bottom value
dim end as n'this is the top value
dim i as n 'to be used as a counter in the loop
dim vtotal as n
start=101
end = 302

while i<=1
vtotal=int((end-start)/2)+1+(int((end-start)/2)+1)*if(mod(start,2)=0,start-2,int(start/2)*2)+(int((end-start)/2)+1)^2
i=i+1
end while
msgbox("The total sum is: "+vtotal+" and the script used 1 loop")

There is only one loop, about as few as you can get unless I hire the real smart alec lawyer who will argue for my original expression to be the ultimate winner as it has zero loops!! But I don't think the panel of judges will buy that.

As you can see, even if the judges accept the logic of zero loops or one loop, still I wont get any prizes since I am still in violation of the rules since I didn't explain how and why does that expression work, and I wont.. To understand this expression, you have to mentally translate this math puzzle into a geometric one..to explain that is a bit time consuming and outside the parameters of this puzzle, so we will move on to a more realistic solution, which I will start in a new post and and ask you to please ignore this post as a side show that may or may not have any redeeming value.

G Gabriel
12-26-2011, 01:38 PM
So, on to a more realistic solution, one that complies with the spirit rather than the letter of the rules.
My first instinct was to:
1-identify the first even number
2-Loop stepping by 2 adding the values until reach the top value.
I ended up with 100 loops. That's embarrassing! a hundred loop to solve a simple puzzle like this? There got to be a better way.
There is..
One that uses a 20 loops or few more.
Here it is:
P.S.: To best read the introduction in case your screen rsolution is different from mine, copy/paste it into Word and read it in Word.

'Introduction:
'The object is to sum all even values between 2 given numbers
'Since these 2 numbers are provided in the puzzle, meaning I could hard-code these values which makes everything a lot simpler and faster but just in case the intent was to solve for any numbers not just the ones provided in the puzzle, the script is written so that you can substitute these number at will and get the correct result.
'
'Let me first start with the logic behind the script.
'To add all even values between 2 given numbers, you identify the first even number, then add 2 to it and add the new number to the previous one and so on..
'That's the standard way of thinking.. by doing that you will have to loop as many times as there are even values..
'That's too many loops and too expensive..
'
'Let's look at the puzzle from a different perspective..
'
'In the example provided, the first even number is 102.
'Let's call this number a base.
'Every subsequent number is 2 points more than the one before..
'Let's get away from this line of thinking.
'A different way to think about is:
'You have a base number, then
'Every subsequent number has one more 2 than the one before, i.e.:
'The base number is 102
'The one after has one more 2 than the base: 104
'The one after has two more 2's than the base: 106
'The one after has three more 2's than the base: 108
'and so on..
'
'Now if I strip the base of its 2, then we could re-state the above as follows:
'Instead of the base, I am going to have new figure, will call it the "denominator" which is the base stripped off its 2, i.e. 102-2=100
'
'Now the first even value (the base, 102) has one 2 more than the denominator and
'The second even value (104) has two 2's more than the denominator
'The third even value (106) has three 2's more than the denominator
'and so on..
'
'so now I could deal with 2 sets of values:
'The first set, we will call it the "Denominator-cluster" is basically made up of the even values stripped off their 2's. meaning, they are all 100
'
'The second set, we will call it the "Two-cluster" is made up of those 2's that are above and beyond the denominator. This is a series made up as one 2, two 2's, three 2's... ten 2's.
'
'Now I am going to break up all the even values between 101 and 302 into 10 clusters.
'As you can see, the "Denominator-clusters" will each have 10 equal values. the first cluster will have 10 equal values each of 100. If I loop through these clusters and step increment each cluster by 20 (10 2's), the second cluster will have 10 equal values of 120 each, the third cluster will have 10 equal values of 140 each.. and so on.
'
'To this cluster, I need to add the cluster of 2's. I need to calculate this cluster only once and add it to each one of the "denominator-clusters" and then add all the clusters together which gives me the final total sum.
'
'To add the cluster of 2's, I could hard-code that:
'2+4+6+8...+20=110
'But once again, if the intent of the puzzle is to be able to substitute for other values, I will use a loop to add these incrementing 2's, which means I will loop 10 times to calculate the cluster of 2's then loop another 10 times to calculate the "denominator-clusters" and in each loop I am adding each one of the to the previous total plus the sum of the cluster of 2's so at the end of the last loop. After that I will find the orphan values, the ones that were not included in the clusters and add those to the total which gives me the grand total.
'Now why did I choose 10 clusters?
'That produces the "optimal" number of loops in this scenario:
'If you increase the size of the cluster to reduce their number and thus the number of looping through them, you will increase the number of 2's and the number of their loops.
'How to arrive at the optimal cluster size?
'That's for another day another post, but regardless, any number of clusters will beat the standard looping method.

Here is the script:

'For further explanations, please read the Introduction section
option strict
dim bottom_num as n
dim top_num as n
dim denominator as n
dim span as n 'the span between the bottom and top numbers
dim values_num as n
dim i as n 'to be used as a counter
dim twos as n'this will add the 2's that are above and beyond the denominator values
dim vtotal as n=0
dim trail_num as n'number of orphan values not in the clusters
dim trail_values as n'the actual value of the orphan
dim loop_num as n'how many times we looped so far
dim last_even as n'this is the value of top-most even number in the series
bottom_num=101
top_num=302
span=top_num-bottom_num
values_num=int(span/2)+1 'This is how many even number in the span between the bottom and top numbers. The 1 is added to make it all inclusive, i.e. including the bottom as well as the top numbers
trail_num=mod(values_num,10)
denominator=bottom_num-if(mod(bottom_num,2)=0,0,1)
'First will add the "Two-cluster"
for i=1 to 10
twos=twos+i*2
next i
loop_num=i
'Now we will iterate over the "denominator-clusterss" , each cluster will have a denomiator value of 20 more the one before
for i=1 to 10
vtotal=vtotal+(denominator+20*(i-1))*10+twos
next i
loop_num=loop_num+i
'Now we will add the trailing numbers, those that were not included in the 10 clusters
'Find the last even number:
last_even=if(mod(top_num,2)=0,top_num,top_num-1)
for i= 1 to trail_num step-1
trail_values=trail_values+last_even
last_even=last_even-2
next
loop_num=loop_num+1
vtotal=vtotal+trail_values
msgbox("The sum total of all even numbers is: "+vtotal+" "+"and the number of loops is: "+loop_num)