help in a question

link
Can someone please help me how to solve this problem.
Thank you

Constraints for So,S1,N < 10^9