ACCEPTED !!! The UVa forum posts contain very handy test cases..
____________________________________________________________________
Question: Multifactorials
____________________________________________________________________
#include "iostream.h"
#include "math.h"
long long int max = pow(10, 18);
int primes[1000], pcount;
int isPrime(int n) {
double sq = sqrt(n);
for(int i = 2; i <= sq; i++) if(n % i == 0) return 0;
return 1;
}
void updateFactors(int t, int *pfactorcount) {
for(int i = 0; i < pcount; i++) {
int p = primes[i];
while(t % p == 0) {
t /= p;
pfactorcount[p]++;
}
if(t == 1) break;
}
}
long long int multiFactovisors(int n, int k) {
int stop;
if(k == 0) stop = n;
else {
if(n % k == 0) stop = k;
else stop = n % k;
}
int pfactorcount[1000];
for(int i = 0; i < 1000; i++) pfactorcount[i] = 0;
int i = 0;
while(1) {
int t = n - k * i;
updateFactors(t, pfactorcount);
i++;
if(t == stop) break;
}
long long int prod = 1;
for(int i = 0; i < pcount; i++) {
prod *= (pfactorcount[primes[i]] + 1);
if(prod > max || prod < 1) return 0;
}
return prod;
}
int main()
{
int pindex = 0;
for(int i = 2; i < 1000; i++) if(isPrime(i)) primes[pindex++] = i;
pcount = pindex;
int t;
cin >> t;
for(int i = 1; i <= t; i++) {
char inp[25];
cin >> inp;
int n = atoi(inp);
long long int r;
if(n <= 0) r = 1;
else {
int j;
for(j = 0; inp[j] != '!'; j++);
int k = strlen(inp) - j;
r = multiFactovisors(n, k);
}
cout << "Case " << i << ": ";
if(r > 0) cout << r << endl;
else cout << "Infinity\n";
}
return 0;
}____________________________________________________________________
Monday, December 10, 2007
Multifactorials
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment