Skip to content

Instantly share code, notes, and snippets.

@jdspiral
Last active March 2, 2016 01:27
Show Gist options
  • Save jdspiral/553130bc8a441320e699 to your computer and use it in GitHub Desktop.
Save jdspiral/553130bc8a441320e699 to your computer and use it in GitHub Desktop.
Determine if secret() is additive or not.
<?php
/**
*
* Author: Josh Hathcock
*
* You are given a function 'secret()' that accepts a single integer parameter and returns an integer. In your
* favorite programming language, write a command-line program that takes one command-line argument (a number)
* and determines if the secret() function is additive [secret(x+y) = secret(x) + secret(y)], for all
* combinations x and y, where x and y are all prime numbers less than the number passed via the command-line
* argument. Describe how to run your examples. Please generate the list of primes without using built-in
* functionality.
*
* To execute this script run:
* $ php secret.php #
*
* where "#" is an integer parameter
*
*/
if (!isset($argv[1]) || !is_numeric($argv[1])) {
cli("Please enter an integer as a parameter.");
exit;
}
$limit = intval($argv[1]);
// Secret function
function secret($num) {
return $num;
}
// Get primes using Sieve of Eratosthenes
function sieve($limit){
if (!is_int($limit)) {
return false;
}
if ($limit < 1) {
return false;
}
$primes = array(1);
if ($limit == 1) {
return $primes;
}
$primes = array_fill(0, $limit, true);
for ($n = 2; $n < $limit; $n++) {
if ($primes[$n]) {
for ($i = $n*$n; $i < $limit; $i += $n) {
$primes[$i] = false;
}
}
}
return $primes;
}
// Function to test is the 2 numbers are additive
function testSecret($primes) {
$used = array();
foreach ($primes as $x) {
foreach ($primes as $y) {
if (!in_array($y, $used)) {
$test1 = secret($x + $y);
$test2 = secret($x) + secret($y);
if ($test1 != $test2) {
return false;
}
}
}
$used[] = $x;
}
return true;
}
// Get the primes of our number
$primes = sieve($limit);
// Now test
if (testSecret($primes)) {
echo "secret() is additive!\n";
}
else {
echo "secret() is not additive\n";
}
function cli($message) {
print $message . PHP_EOL;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment