NEWTON

NEWTON


Popular tags

    Cairo: How do write a log function in Cairo

    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

    1 answers

    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

    Your answer

    NEWTON

    NEWTON