Skip to content

Instantly share code, notes, and snippets.

@robot-dreams
Last active March 18, 2018 05:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robot-dreams/32f473288486fde268f49a03b7142315 to your computer and use it in GitHub Desktop.
Save robot-dreams/32f473288486fde268f49a03b7142315 to your computer and use it in GitHub Desktop.
Project Euler #1 as an Ethereum contract (written in Solidity)
pragma solidity ^0.4.0;
contract ProjectEuler001 {
// For the low price of 1000 wei, you can solve Project Euler Problem 1!
uint price = 1000;
event Solved(uint n, uint result);
// Returns the n-th triangular number 1 + 2 + ... + n
function t(uint n) private pure returns (uint) {
return n * (n + 1) / 2;
}
// Solves Project Euler Problem 1 for the given input parameter (the input
// for the actual problem should be 1000)
function Solve(uint n) public payable {
// This is not a charity :)
require(msg.value >= price);
// Subtract 1 since we only sum values strictly less than n
uint m = n - 1;
// Using inclusion-exclusion, the desired sum is
// (3 + 6 + ...) + (5 + 10 + ...) - (15 + 30 + ...)
// = 3 * (1 + 2 + ...) + 5 * (1 + 2 + ...) - 15 * (1 + 2 + ...)
emit Solved(n, 3 * t(m / 3) + 5 * t(m / 5) - 15 * t(m / 15));
}
}
@robot-dreams
Copy link
Author

This contract is deployed at address 0x5dD7BAFD0e478e73721D9AE9C6D9725a042F7dae

@jsgoller1
Copy link

sploosh

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment