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.If you recall - natural numbers are simply positive whole numbers (no decimals!).So my first impression as to tackling this problem is to loop a number from 1 to 999 and divide by 3 and 5 along the way. Anything that divides with no remainder goes evenly into the number and should be added to a running total.
Find the sum of all the multiples of 3 or 5 below 1000.
Ok, sounds easy enough. but i'll need to know what the syntax is for a for loop and an if statement.
For Loop syntax:
for (initial condition variable; condition is some circumstance; increment the original variable to progress through the loop).
Lets look at an example and use the knowledge that we need to loop from 1 to 999
Example:
for (x = 1; x <= 999; x++)
{
do stuff hereIf Statement syntax:
}
if (variable <operator> equals result)
Example:
if(x%3 == 0)Mod command:
{
do stuff
}
Now the "%" symbol is called mod. The mod command returns the remainder of the division of x divided by 3. This is useful to us in this question to check if 3 or 5 goes evenly into x.
Or Command:
Double pipe "||" is the or statement in C#, we'll be using that to see if x%3 or x%5 is 0.
So my entire code solution for this problem is:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int x = 1;
int y = 0;
for (x = 1; x < 1000; x++)
{
if (x % 3 == 0 || x % 5 == 0)
y = y + x;
}
Console.WriteLine("The Answer is: ");
Console.WriteLine(y);
}
}
}
This seems to run pretty darn fast and outputs the correct statement. I've chosen to run a console application from the projects window and use Crtl + F5 to have the console window stay open after I run the code.I will work on better code formatting in future posts but as you can see we're simply looping from 1 to 999 and dividing by 3 and 5 at each loop. If the remainder is zero we add it to our running total variable of "y".
No comments:
Post a Comment