Here's one solution:
contract Ceil {
function ceil(uint a, uint m) constant returns (uint ) {
return ((a + m - 1) / m) * m;
}
// To measure gas
function ceil1(uint a, uint m) returns (uint ) {
return ((a + m - 1) / m) * m;
}
}
And testing for the correct results:
> ceil.ceil(123456, 1000)
124000
> ceil.ceil(1,1000)
1000
> ceil.ceil(0,1000)
0
> ceil.ceil(123000,1000)
123000
To measure the gas, I've created ceil1(...)
and sent a transaction:
> ceil.ceil1(123456, 1000, eth.accounts[0], {
from:web3.eth.accounts[0],
data: ceilCompiled.Ceil.code,
gas: 1000000
});
"0xeac6bb84ba5a1703ee3a762cb392f1793adf550906b6112e441928c0ea288f53"
...
> debug.traceTransaction("0xeac6bb84ba5a1703ee3a762cb392f1793adf550906b6112e441928c0ea288f53")
{
gas: 21990,
returnValue: "000000000000000000000000000000000000000000000000000000000001e460",
structLogs: [{
The gas cost of this calculation is 21,990. This figure would include the default 21,000 gas for sending a regular transaction which gives an incremental gas cost of 990.
When plugging the code into the Online Solidity Compiler at https://chriseth.github.io/browser-solidity/#version=soljson-latest.js, the following gas cost are estimated:
Creation: 69 + 43000
External:
ceil(uint256,uint256): 275
ceil1(uint256,uint256): 253
Internal:
So an estimate for the gas cost of ceil1(...)
is between 253 and 990.