Since S is finite, there is a finite set of all functions {g1,g2,…,gk} from S to itself. Consider a function F that assigns to each positive integer n one of these functions such that f is the n-th power of the function F(n). So F induces a partition of the set of all positive integers into sets Pi consisting of all the integers n such that F(n)=gi.
For any positive integer N, consider the complete graph KN on N vertices labeled 1 through N. We will colour the edges of KN in k colours C1,C2,…,Ck according to the partition in the following way: If ∣x−y∣ lies in Pi, colour the edge between x and y in the colour Ci. By Ramsey's theorem we can take N to be large enough that there is a monochromatic triangle in KN. This means that there are three integers x,y and z and an index i for which ∣x−y∣,∣y−z∣,∣z−x∣∈Pi. Hence there are three integers a,b,c∈Pi such that a+b=c.
Therefore, some function gi:S→S satisfies f(x)=gia(x)=gib(x)=gia+b(x) for each x∈S. Hence, f(f(x))=gia(gib(x))=gia+b(x)=f(x) for each x∈S.
Remark: The fact that there is an index i for which Pi contains three integers a,b,c such that a+b=c is known as Schur's theorem.