program eins;
const
infile='eins.in';
outfile='eins.out';
var
t:longint;
n,p:qword;
function Fibonacci(n,p:qword):qword;
var a,b,c:qword;
begin
a:=0;b:=1;
while n>1 do begin
c:=(a+b) mod p;
a:=b;b:=c;
dec(n);{ writeln(c); }
end;
exit(c);
end;
begin
assign(input,infile);reset(input);
assign(output,outfile);rewrite(output);
readln(t);
while t>0 do begin
readln(n,p);
writeln(Fibonacci(n,p));
dec(t);
end;
close(input);close(output);
end.