Given an integer, write a function findSum
that returns the sum of all multiples of 3 or 5 up to up to n.
findSum(8) returns 5
findSum(33) returns 10
Simple
function findSum(n) {
let sum = 0;
for (let i=0; i<=n; i++) {
if (i%3==0 || i%5==0) sum += i;
}
return sum;
}
Functional
const findSum = (n) => (
Array.from({ length: n+1}, (v,i) => i)
.filter(o => (o%3==0) || (o%5==0))
.reduce((a, b) => a+b)
);
namespace Solution
{
public static class Program
{
public static int findSum(int n)
{
int sum = 0;
for(var i=0; i<=n; i++) {
if (i % 3 == 0 || i % 5 == 0) sum += i;
}
return sum;
}
}
}
using System.Collections.Generic;
namespace Solution
{
public static class Program
{
public static int findSum(int n)
{
List<int> found = new List<int>();
for(var i=0; i<=n; i++) {
if (i % 3 == 0 || i % 5 == 0) {
found.Add(i);
}
}
int sum=0;
foreach (var num in found) {
sum += num;
}
return sum;
}
}
}
using System.Collections.Generic;
using System.Linq;
namespace Solution
{
public static class Program
{
public static int findSum(int n)
{
List<int> found = new List<int>();
for(var i=0; i<=n; i++) {
if (i % 3 == 0 || i % 5 == 0) {
found.Add(i);
}
}
return found.Sum();
}
}
}
using System.Collections.Generic;
using System.Linq;
using System;
namespace Solution
{
public static class Program
{
public static int findSum(int n)
{
var f = Enumerable.Range(1, n)
.Where( o => (o%3 == 0) || (o%5==0))
.Aggregate( (a, b) => a+b);
Console.WriteLine(f);
return f;
}
}
}
Write a function findSum(array)
that returns the sum of all squares in the array.
findSum([1, 2, 3]) returns 15
findSum([2, 5]) returns 34
function squareSum(numbers){
let sum=0;
for (let val of numbers) sum += val*val;
return sum;
}
function squareSum(numbers){
return numbers.reduce((a,b) => a+(b*b));
}
public static class Kata
{
public static int SquareSum(int[] n)
{
int sum=0;
foreach (int val in n) {
sum += val*val;
}
return sum;
}
}
using System.Linq;
public static class Kata
{
public static int SquareSum(int[] n)
{
return n.Select(v => v*v).Sum();
}
}