Let Tag = x bits, Set = y bits, Block Offset = z bits.
So, x + y + z = 40.
Cache Size = 512KB = 219B.
Number of cache lines = $\frac{2^{19}}{2^{z}}$ = 2(19-z)
Given the cache is 8 way set associative.
So, number of sets = $\frac{2^{(19-z)}}{2^{3}}$ = 2(16-z)
From the first equation,
x + (16-z) + z = 40
So, x = 24 bits