#include<stdio.h>#include<string.h>int N , K ;void solve(){ int res = 0 , mid , n = N , mm; while(n >= 1){ int pos = -1 ; int cc = 0 ; for(int temp=n ;temp;){ if(temp%3 == 2){ pos = cc ; mm = temp ; mid = temp / 3 ; } cc ++ ; temp /= 3 ; } if(pos == -1){ res = (res + n) % K ; n-- ; continue ; } for(int c=0;c<pos;c++) mm = mm * 3 ; res = ( res + mid*((n-mm+1)%K)%K ) % K ; n = mm - 1 ; } printf("%dn",res);}int main(){ while(scanf("%d %d",&N,&K) == 2){ solve(); } return 0;}


