Question

Me again, second time poster, already I like this community!

Now I have a function problem. The goal is to use the function =Problem1Function(MaxNumber) to sum all multiples of 3 and multiples of 5 below the input value MaxNumber.

To do this I am using two do-while loops with conditions (MultOfThree < MaxNumber) and (MultOfFive < MaxNumber) respectively.

To do this, I only need to know how to generate new variables within the loop. I know this means the variable declaration must be in the loop, but I'm not sure of the following:

How tdo you make the loop generate a new variable name each time through? I need this so each new variable (which will be a multiple of 3 or 5) doesn't get overwritten, and I can sum them in the end. An example would be variable names of MultOfThree1,MultOfThree2,MultOfThree3, etc. Then at the end I can sum those.

I have the beginning of my function code already, I don't think it'll help to post it, but I will upon request.

The code is in excel VBA. Sorry forgot that in original post.

Was it helpful?

Solution

Ok, please read all of this after I give you the answer: NO, there is no way to create variable names.

Now, I realize that this doesn't answer your question, but there is a more efficient way of doing this using some algebra and a trick developed by Gauss. Say your number is 46. You can find the largest multiple of three by using integer division, which will truncate the result. 46 / 3 * 3 = 45. Naturally, the lowest multiple of three is 3, so your multiples of three are 3, 6, 9, 12, ..., and 45. Now using Gauss's trick for adding a series of numbers n(n + 1)/2, (generalized for multiples to n(n+a)/2a), you can get the total by doing 45(45+3)/(2*3)=360. Follow the same procedure for multiples of five and add that to the multiples of three, and you will have your answer!

If you are still intent on doing it the way you described, you must use an array (or vector if you're using the C++ template). However, my method takes considerably less processing time and is much more elegant. Optimizations like this are good to know and fun to puzzle out! Good luck!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top