<?php
/**
 * Author: David Mottern
 * This was inspired by Project Euler problem 1.
 * https://projecteuler.net/problem=1
 * It's not meant to be a final polished project.
 * 
 * Multiples of 3 and 5
 * 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.
 * 
 * I've written a more general solution where you can pass any number of divisors (json encoded)
 * as well as an "upto" number.
 * This is live on the web at http://mottern.com/projecteuler/Problem1/
 * To solve for the problem described, for example, you would call it as follows:
 *         http://mottern.com/projecteuler/Problem1/?divisors=[3,5]&upto=1000
 * This will also work if the values are sent in a Post rather than a Get.
 */
    
function sum_of_multiples($divisors$upto) {
        
/*
         * Given an array of integer divisors, and a maximum value
         * sum all integers from 1 to the maximum that are divisible
         * by one of the divisors.
         * 
         * @param array $divisors
         *         An integer array of the divisors to be tested.
         * 
         * @param int $upto
         *         The maximum value up to which we want to test.
         * 
         * @return int
         *         The final sum.
         */
        
$sum 0;
        for(
$n=min($divisors); $n $upto$n+=1) {
            foreach(
$divisors as $divisor) {
                if (
$n $divisor == 0) {
                    
// If $n is divisible by $divisor, add to the sum and break out of foreach.
                    // We only care that it's divisible by at least one of the divisors.
                    
$sum += $n;
                    break;
                }
            }
        }
    return 
$sum;
    }

    
set_error_handler("warning_handler"E_WARNING); // Show usage message for both errors and warnings.

    
function warning_handler() {
        throw new 
Exception();
    }

    
// Main Code
       
try {
           if (isset(
$_REQUEST['show_source'])) {
            
show_source(__FILE__);
            exit;
        }
           
$divisors json_decode($_REQUEST['divisors']);
        
$total sum_of_multiples($divisors$_REQUEST['upto']);
        echo 
$total;
    } catch (
Exception $e) {
//        Show the usage message regardless of the exception type.
        
echo 'usage: <i>index.php?divisors=[x,y...]&upto=n</i> with integer values greater than 0.';
        echo 
'<br>View PHP source: <A href="http://mottern.com/projecteuler/Problem1/?show_source">http://mottern.com/projecteuler/Problem1/?show_source</A>';
    }
?>