Skip to content

faster uint256_add. No new hints needed. #176

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 29 additions & 9 deletions src/starkware/cairo/common/uint256.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,6 @@ func felt_to_uint256{range_check_ptr}(value: felt) -> Uint256 {
// Adds two integers. Returns the result as a 256-bit integer and the (1-bit) carry.
func uint256_add{range_check_ptr}(a: Uint256, b: Uint256) -> (res: Uint256, carry: felt) {
alloc_locals;
local res: Uint256;
local carry_low: felt;
local carry_high: felt;
%{
Expand All @@ -79,14 +78,35 @@ func uint256_add{range_check_ptr}(a: Uint256, b: Uint256) -> (res: Uint256, carr
ids.carry_high = 1 if sum_high >= ids.SHIFT else 0
%}

assert carry_low * carry_low = carry_low;
assert carry_high * carry_high = carry_high;

assert res.low = a.low + b.low - carry_low * SHIFT;
assert res.high = a.high + b.high + carry_low - carry_high * SHIFT;
uint256_check(res);

return (res, carry_high);
if (carry_low != 0) {
if (carry_high != 0) {
tempvar range_check_ptr = range_check_ptr + 2;
tempvar res = Uint256(low=a.low + b.low - SHIFT, high=a.high + b.high + 1 - SHIFT);
assert [range_check_ptr - 2] = res.low;
assert [range_check_ptr - 1] = res.high;
return (res, 1);
} else {
tempvar range_check_ptr = range_check_ptr + 2;
tempvar res = Uint256(low=a.low + b.low - SHIFT, high=a.high + b.high + 1);
assert [range_check_ptr - 2] = res.low;
assert [range_check_ptr - 1] = res.high;
return (res, 0);
}
} else {
if (carry_high != 0) {
tempvar range_check_ptr = range_check_ptr + 2;
tempvar res = Uint256(low=a.low + b.low, high=a.high + b.high - SHIFT);
assert [range_check_ptr - 2] = res.low;
assert [range_check_ptr - 1] = res.high;
return (res, 1);
} else {
tempvar range_check_ptr = range_check_ptr + 2;
tempvar res = Uint256(low=a.low + b.low, high=a.high + b.high);
assert [range_check_ptr - 2] = res.low;
assert [range_check_ptr - 1] = res.high;
return (res, 0);
}
}
}

// Splits a field element in the range [0, 2^192) to its low 64-bit and high 128-bit parts.
Expand Down