Currently, I am working on a coding exercise that involves finding the sum of multiples of 3 and 5 below a given number.
The task is to create a function called ThreeFiveMultiples(num) that will calculate this sum. For instance, if the input num is 10, the multiples of 3 and 5 below 10 are 3, 5, 6, and 9, totaling 23. Therefore, the program should return 23. The input integer will always be between 1 and 100.
I am struggling with my C# solution as it keeps throwing an error: System.IndexOutOfRangeException: Index was outside the bounds of the array.
using System;
using System.Linq;
class MainClass {
public static int ThreeFiveMultiples(int num) {
int[] array = new int[] {};
for(var i = num-1; i > 1; i--)
{
if(i % 5 == 0 || i % 3 == 0)
{
array[i] = i;
}
}
return array.Sum();
}
Here is a different approach using JavaScript:
function ThreeFiveMultiples(num) {
var arr = [];
var tot=0;
for(var i=num-1; i>1; i--){
if(i % 5 === 0 || i % 3 === 0){
arr.push(i);
}
}
for(var i=0; i < arr.length; i++){
tot = tot + arr[i];
}
return tot;
}