SGU 118 – Recursion

/* Note that f(A1*A2) = f(f(A1)*f(A2))
 * and f(A1+A2) = f(f(A1)+f(A2))
 * So use recursion
 */
#include<cstdio>
int n,x[1005];
int d(int x)
{
	int s=0;
	while(x>0) s+=x%10, x/=10;
	if(s<10) return s;
	else return d(s);
}
int f(int i)
{
	if(i==n-1) return d(x[i]);
	else return d(d(x[i])*d(1+f(i+1)));
}
int main()
{
	int t; scanf("%d",&t);
	while(t--)
	{
		scanf("%d",&n);
		for(int i=0;i<n;i++) scanf("%d",x+i);
		printf("%d\n",f(0));
	}
	return 0;
}

Leave a Reply

Your email address will not be published.