Search code examples
kdb

Find even numbers upto n in kdb?


Can you please help to write optimized function to find even numbers upto n without mod and scanning each element in upto n number.

I didn't understand below kdb code to find even number, please explain me below function.

is x even

x:1 2 3 4 5

~x!2

0 1 0 1 0

how do I convert kdb code into q function?

I found an example on google, however do not want this solution. I found better solution in kdb and not able to convert kdb code to Q.

L:til 100
{ $[0~(x mod 2);-1 string[x]," is even"; -1 string[x]," is not"]} each L;

Solution

  • I don’t fully understand your question. But you could try something like:

    //Function to generate even numbers up to N excluding 0
    /x div 2 reduces the list length by half that kdb has to generate using til
    /i.e. it does not have to generate the full list up to N then filter the even numbers, hence optimized
    {2*1+til x div 2}
    //Function to filter even numbers from list input
    /x mod 2 is a test to check if number is odd
    {x where not x mod 2}