Created
July 5, 2023 01:01
-
-
Save QEDK/b61f81071dbfa1c52caef571ae928138 to your computer and use it in GitHub Desktop.
Evens contract
This file contains hidden or 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
// SPDX-License-Identifier: AGPL-3.0 | |
pragma solidity 0.8.20; | |
contract Evens { | |
function getEvens(uint256 startNum, uint256 endNum) external pure returns (uint256) { | |
assembly("memory-safe") { | |
// skip first iteration if startNum is 0 | |
if iszero(startNum) { startNum := add(startNum, 1) } | |
endNum := add(endNum, 1) | |
let num := 0 | |
for { let i := startNum } lt (i, endNum) { i := add(i, 1) } { | |
// use masking here to save gas | |
if iszero(and(0x0000000000000000000000000000000000000000000000000000000000000001, i)) { | |
num := add(num, 1) | |
} | |
} | |
// shave off some gas by skipping typecheck | |
mstore(0, num) | |
return (0, 32) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment