Problem 1

Posted on Nov 18, 2022

Problem

Find the sum of all the numbers evenly divisible by 3 or 5 below 1000.

General solution

Given the small search space, the simplest solution is to iterate over the numbers from 1 to 999 and add them to a running total if they are evenly divisible by 3 or 5.

Solution: Go

package main

import (
	"fmt"
)

func main() {
	var sum int = 0
	
	for num := 1; num < 1000; num++ {
		if num % 3 == 0 || num % 5 == 0 {
			sum += num
		}
	}

	fmt.Println(sum)
}

Solution: PHP

<?php

declare(strict_types=1);
error_reporting(E_ALL);

$sum = 0;

for ($num = 1; $num < 1000; $num++)
{
    if ($num % 3 === 0 || $num % 5 === 0)
    {
        $sum += $num;
    }
}

print("$sum\n");

Solution: C

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
  int sum = 0;

  for (int i = 1; i < 1000; i++)
  {
    if (i % 3 == 0 || i % 5 == 0)
    {
      sum += i;
    }
  }

  printf("Sum of multiples of 3 or 5 below 1000: %d\n", sum);

  return EXIT_SUCCESS;
}