Last active
March 18, 2018 05:39
-
-
Save robot-dreams/32f473288486fde268f49a03b7142315 to your computer and use it in GitHub Desktop.
Project Euler #1 as an Ethereum contract (written in Solidity)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This contract is deployed at address
0x5dD7BAFD0e478e73721D9AE9C6D9725a042F7dae