I will explain for 6, same logic applies for all the numbers.
if 6 persons shakes will all in the party, then number of shakes will be:
A B C D E F
A can shake with only rest of 5 persons(B,C,D,E,F) i.e, right side ppl. = 5
B can shake with only his right sides(C,D,E,F) ppl(not with A bcos,A already shook with B just now. so no repeat) = 4
C can shake with only his right sides(D,E,F) ppl(not with A&B bcos,A&B already shook with C just now. so no repeat) = 3
D can shake with only his right sides(E,F) ppl(not with left side ppl bcos, they already shook with D just now. so no repeat) = 2
E can shake with only his right sides(F) ppl(not with left side ppl bcos, they already shook with E just now. so no repeat) = 1
as all of the persons shook hand with F, He dont shake with any one now.
So total possible shakes for 6 persons are = 5+4+3+2+1 => 15
now in questions it is given that, No one shakes hand with neighbors.
Imagine ppls sitting around table
Please treat above image as 6 Ppl around circle :
A cannot shake with B,F . I am representing it as below :
A -no- B & F => 2 invalid shakes.
B -no- C only. Bcos B -no- A is covered as part of first case.
=> 1 invalid shake
C -no- D only. => 1 invalid shake
D -no- E only. => 1 invalid shake
E -no- F only. => 1 invalid shake
F dont shake with A is already covered as part of first invalid shakes.
so total invalid shakes are 2+1+1+1+1 = 6
so for 6 ppl: out of total 15 , 6 are invalid. So 15-6 = 9
on the same line :
for 17 ppl: out of total (16+15+...+1)=136 , 17 are invalid. So 136-17 = 119
shortcut : For N ppl, Total shakes are (N-1)(first term + last term)/2 Arithmetic progression sum. out of which Invalids are N.
So valid shakes => (Total - N)