http://projecteuler.net/problem=1
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. Find the
sum of all the multiples of 3 or 5 below 1000.
If I change “int maxNum” to 10 or any other small number like 20, I’m getting the right answer.
But somehow when I do it with a big number like 1000, it will give me a number which I don’t expect to come, I don’t know why, please help.
Does it do it because it has reach the max value of an int?
class Program
{
static void Main(string[] args)
{
//TASK: 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.
//Find the sum of all the multiples of 3 or 5 below 1000.
int multiplierA = 3;
int multiplierB = 5;
int maxNum = 1000;
int i = 1;
int deelEen = MultiplyFactory(multiplierA, i, maxNum);
int deelTwee = MultiplyFactory(multiplierB, i, maxNum);
int result = deelEen + deelTwee;
Console.WriteLine(result);
Console.Read();
}
static int MultiplyFactory(int multiplier, int i, int maxNum)
{
List<int> savedNumbers = new List<int>();
while(multiplier*i < maxNum)
{
savedNumbers.Add(multiplier*i);
i++;
}
int answer = 0;
foreach(int getal in savedNumbers)
{
Console.WriteLine(getal);
answer = answer + getal;
}
savedNumbers.Clear();
return answer;
}
}
I think the problem is that you need to find sum of all the multiples of 3 OR 5. And what your program is doing is finding sum of all multiplers of 3 + sum of all multipliers of 5.
You can return arrays of int and then sum distinct numbers from arrays.
You can also use Linq to get distinct values from lists