Skip to content

Instantly share code, notes, and snippets.

@milancermak
Last active September 1, 2023 09:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save milancermak/adf6c70cdd550155a754e335d92fcbf5 to your computer and use it in GitHub Desktop.
Save milancermak/adf6c70cdd550155a754e335d92fcbf5 to your computer and use it in GitHub Desktop.
Cairo pow comparison
fn pow_old(base: u128, mut exp: u128) -> u128 {
if exp == 0 {
1
} else {
base * pow_old(base, exp - 1)
}
}
fn pow_new(base: u128, exp: u128) -> u128 {
if exp == 0 {
1
} else if exp == 1 {
base
} else if exp % 2 == 0 {
pow_new(base * base, exp / 2)
} else {
base * pow_new(base * base, (exp - 1) / 2)
}
}
#[test]
#[available_gas(10000000)]
fn test_pow_old_1() {
assert(pow_new(2, 4) == 16, 'old 1')
}
#[test]
#[available_gas(10000000)]
fn test_pow_old_2() {
assert(pow_old(80, 13) == 5497558138880000000000000, 'old21')
}
#[test]
#[available_gas(10000000)]
fn test_pow_old_3() {
assert(pow_old(14, 30) == 24201432355484595421941037243826176, 'old 3')
}
#[test]
#[available_gas(10000000)]
fn test_pow_new_1() {
assert(pow_new(2, 4) == 16, 'new 1')
}
#[test]
#[available_gas(10000000)]
fn test_pow_new_2() {
assert(pow_new(80, 13) == 5497558138880000000000000, 'new 2')
}
#[test]
#[available_gas(10000000)]
fn test_pow_new_3() {
assert(pow_new(14, 30) == 24201432355484595421941037243826176, 'new 3')
}
cairo-test --single-file ./pow.cairo

test pow::pow::test_pow_old_1 ... ok (gas usage est.: 91580)
test pow::pow::test_pow_old_2 ... ok (gas usage est.: 173990)
test pow::pow::test_pow_old_3 ... ok (gas usage est.: 381050)
test pow::pow::test_pow_new_1 ... ok (gas usage est.: 91580)
test pow::pow::test_pow_new_2 ... ok (gas usage est.: 120950)
test pow::pow::test_pow_new_3 ... ok (gas usage est.: 150320)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment