while 1:n,b=map(int,raw_input().split());k=b**7-1;print n**7/k%k