NEWTON

NEWTON


Popular tags

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

    Asked

    6 months ago

    7

    views


    0

    I am looking for n % 2 = 0 operation

    This question was originally posted on Triality

      cairocairo-lang

    2 answers

    0

    from starkware.cairo.common.math import unsigned_div_rem

    

    func is_even{range_check_ptr}(x) -> (res):

    let (_, is_odd) = unsigned_div_rem(x, 2)

    return (res=1 - is_odd)

    end

    This answer was originally posted on Triality

    answered

    6 months ago

    0

    You can use bitwise operations to check this

    bitwise_and(number, 1) == 0 and #where number is your variable you are testing if even

    This is a code snippet to illustrate the point well

    %builtins bitwise

    from starkware.cairo.common.bitwise import bitwise_and

    from starkware.cairo.common.cairo_builtins import BitwiseBuiltin

    

    func main{bitwise_ptr : BitwiseBuiltin*}():

    let (temp) = bitwise_and(3, 1)

    assert temp = 1

    let (temp) = bitwise_and(4, 1)

    assert temp = 0

    return ()

    end

    This answer was originally posted on Triality

    answered

    6 months ago

    Your answer

    NEWTON

    NEWTON