Finding CB Numbers(logical clarification)

Can you help me understand where is my code going wrong with logic (and is showing 8161 as a CB Number in the example given)

Hello @dhruvprashar,

I have corrected your code:

Refer to comments for better understanding.

Hope, this would help.
Give a like if you are satisfied.