Search code examples
kdb

Looping in Q language


I am trying to figure out Q language basics. I am trying a sample program in which let's say for a given number I can find the sum of all the multiples of 3 and 5?

if input is 10 sum : 23

I am trying to think in terms using of til and sum but cannot but to no avail till now.


Solution

  • q)sum where 0=min(til 10)mod/:3 5
    23
    

    In steps, we just apply our mod over 5 and 3 rather than doing them separately.

    q)(til 10)mod 3
    0 1 2 0 1 2 0 1 2 0
    q)(til 10)mod 5
    0 1 2 3 4 0 1 2 3 4
    q)(til 10)mod/:3 5
    0 1 2 0 1 2 0 1 2 0
    0 1 2 3 4 0 1 2 3 4
    q)
    

    With this result we have 2 lists; ((til 10)mod 3;(til 10)mod 5). If we went to index 3 of each of these we would have (0;3). This means that our number is divisible by 3 but not 5. We only care whether it's divisible by either, so we can take the minimum.

    q)min(til 10)mod/:3 5
    0 1 2 0 1 0 0 1 2 0
    q)
    

    Next we simply find the indexes where mod is zero;

    q)where 0=min(til 10)mod/:3 5
    0 3 5 6 9
    q)
    

    And since these indexes are of the same value as the actual values at those indices, we can just sum them. Giving;

    q)sum where 0=min(til 10)mod/:3 5
    23
    q)
    

    If it were the case that the indices and values at those indices were not equivalent then we would need to index into the original list and sum the values.