Skip to content

Commit

Permalink
Fix U256SquareRoot hint (lambdaclass#1163)
Browse files Browse the repository at this point in the history
* clippy fmt

* lint fix
  • Loading branch information
igamigo authored and kariy committed Jun 23, 2023
1 parent a4d4f11 commit 14cb620
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 11 deletions.
29 changes: 18 additions & 11 deletions src/hint_processor/cairo_1_hint_processor/hint_processor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -612,29 +612,36 @@ impl Cairo1HintProcessor {
remainder_high: &CellRef,
sqrt_mul_2_minus_remainder_ge_u128: &CellRef,
) -> Result<(), HintError> {
let pow_2_128 = Felt252::from(u128::MAX) + 1u32;
let pow_2_64 = Felt252::from(u64::MAX) + 1u32;
let value_low = res_operand_get_val(vm, value_low)?;
let value_high = res_operand_get_val(vm, value_high)?;
let value = value_low + value_high * &pow_2_128;
let pow_2_128 = BigUint::from(u128::MAX) + 1u32;
let pow_2_64 = BigUint::from(u64::MAX) + 1u32;
let value_low = res_operand_get_val(vm, value_low)?.to_biguint();
let value_high = res_operand_get_val(vm, value_high)?.to_biguint();
let value = value_low + value_high * pow_2_128.clone();
let sqrt = value.sqrt();
let remainder = value - &sqrt * &sqrt;
let remainder = value - sqrt.clone() * sqrt.clone();
let sqrt_mul_2_minus_remainder_ge_u128_val =
&sqrt * &Felt252::from(2u32) - &remainder >= pow_2_128;
sqrt.clone() * 2u32 - remainder.clone() >= pow_2_128;

// Guess sqrt limbs.
let (sqrt1_val, sqrt0_val) = sqrt.div_rem(&pow_2_64);
vm.insert_value(cell_ref_to_relocatable(sqrt0, vm)?, sqrt0_val)?;
vm.insert_value(cell_ref_to_relocatable(sqrt1, vm)?, sqrt1_val)?;
vm.insert_value(
cell_ref_to_relocatable(sqrt0, vm)?,
Felt252::from(sqrt0_val),
)?;
vm.insert_value(
cell_ref_to_relocatable(sqrt1, vm)?,
Felt252::from(sqrt1_val),
)?;

let (remainder_high_val, remainder_low_val) = remainder.div_rem(&pow_2_128);

vm.insert_value(
cell_ref_to_relocatable(remainder_low, vm)?,
remainder_low_val,
Felt252::from(remainder_low_val),
)?;
vm.insert_value(
cell_ref_to_relocatable(remainder_high, vm)?,
remainder_high_val,
Felt252::from(remainder_high_val),
)?;
vm.insert_value(
cell_ref_to_relocatable(sqrt_mul_2_minus_remainder_ge_u128, vm)?,
Expand Down
8 changes: 8 additions & 0 deletions src/tests/cairo_1_run_from_entrypoint_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -373,6 +373,14 @@ fn u256_sqrt_zero() {
);
}

#[test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
fn u256_sqrt_max_num() {
let program_data = include_bytes!("../../cairo_programs/cairo-1-contracts/u256_sqrt.casm");

run_cairo_1_entrypoint(program_data.as_slice(), 257, &[], &[1.into()]);
}

#[test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
fn u256_sqrt_big_num() {
Expand Down

0 comments on commit 14cb620

Please sign in to comment.