The main idea of the question is to find out how many in the Nth row of Yanghui's triangle are not divisible by P.
Just follow Lucas's theorem.
#include<bits/stdc++.h> #define ll long long using namespace std; void W(int x,int y){ if(x>4) return; W(x+1,y/10),putchar(y%10+'0');} int n,p,ans,m,C; int main(){ while(scanf("%d%d",&p,&n)==2&&p&&n){ ans=1,m=n,C++; for(;m;m/=p) ans*=(m%p)+1; printf("Case %d: ",C); W(1,ans),puts(""); } return 0; }