NEWTON

Asked

6 months ago

6

views

0

Looking for an implementation of a log function in Cairo

ㅤ
*This question was originally posted on Triality*

- cairocairo-lang

0

This is some code that is not optimized for big numbers, but currently works

``

`%builtins output range_check`

``

`from starkware.cairo.common.serialize import serialize_word`

`from starkware.cairo.common.math_cmp import is_le`

`from starkware.cairo.common.math_cmp import is_not_zero`

`from starkware.cairo.common.math import assert_250_bit`

``

`func main{output_ptr : felt*, range_check_ptr}():`

`let (exp) = findLog(2,33)`

`serialize_word(exp)`

`return ()`

`end`

``

`#Get log base(target) -> say base = 2 and target = 32 then log2(32) = 5. This will give the floor for any decimal value`

`func findLog{range_check_ptr: felt}(base : felt, target : felt) -> (exp : felt):`

`return findPowLarger(base,0,1,target)`

`end`

``

`#Find the next value = base ^ exp such that value is not greater than target`

`func findPowLarger{range_check_ptr: felt}(base : felt, exp : felt, currVal : felt, target : felt) -> (exp : felt):`

`alloc_locals`

`#Getting the next power of the base on this iteration`

`local newVal = base * currVal`

`assert_250_bit(newVal)`

`#This handles flooring scenario`

`let (isLe) = is_le(newVal, target)`

`if isLe == 1:`

`return findPowLarger(base, exp + 1, newVal, target)`

`end`

`#This handles exact match for base ^ exponent = target`

`let (isNotEqual) = is_not_zero(newVal - target)`

`if isNotEqual == 0:`

`return (exp = exp)`

`end`

`return (exp = exp)`

`end`

ㅤ
*This answer was originally posted on Triality*

answered

7 months ago

1

How do I log/print in Cairo 1.0?

0

How do you check if a number is even in Cairo?

0

Cairo: Getting function selector

0

Cairo: How do I initialize an array in cairo

0

Cairo: How to return true from a function?

0

Cairo Error calling function: Expected 'function_name' to be a struct. Found: 'function'.

0

Cairo Passing Functions

0

Cairo: How do I write a custom error message when an assert fails?

0

Cairo: How to return true from a function?

0

What is SHARP in Cairo Language?

0

How to make recursive function in Cairo Lang?

0

Does anyone know how to print a uint256 in protostar tests?

0

Are there situations in which we prefer declaring variables as `local` vs `tempvar`?

0

Is there anything wrong with the testnet?