Tuesday, October 11, 2011

TJU 1156 Niven Numbers Solution




Problem Link

Solution :
    As there is no information about input number, the number can have 100 digits. So, I used string to take input. Then finding digit some will be done simply for all bases 2 <= b <= 10. After that finding modulus of a big number is the issue.
   I have used the idea that,


  • ( a + b) % M = (a % M + b%M) % M
  • ( a * b) % M = (a % M * b%M) % M
C Implementation of the Problem.


#include <stdio.h>

/*Submit Time: 2009-11-04 06:28:23     Language: GNU C++     Result: Accepted
    Pid: 1156     Time: 0.00 sec.     Memory: 720 K.     Code Length: 0.5 K.
*/

int main(){
	long B,i,j,k,l,sum,num;
	char N[101],ch;

	while( scanf("%ld",&B) && B){	
		scanf("%s",N);
		
		sum=0;
		for( i=0; N[i]; i++){
			sum += N[i]-'0';
		}
		num=0;

		for( i=0; N[i]; i++){
			num *= B;
			num %= sum;
			num += N[i]-'0';
			num %= sum;
		}
		if( num%sum == 0)
			printf("yes\n");
		else
			printf("no\n");
	}
	return 0;
}

No comments:

Post a Comment