Cod sursa(job #2139175)

Utilizator fylot3Bogdan Filote fylot3 Data 22 februarie 2018 10:49:16
Problema Factorial Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.24 kb
#include <stdio.h>
#include <vector>
#include <math.h>

#define PLIMIT	100000000

int binarySearch(std::vector<int> &v, int low, int high, int x) {

	if (low > high)
		return -1;

	int mid = low + (high - low) / 2;
	if (v[mid] <= x && x < v[mid + 1])
		return mid;

	if (x < v[mid])
		return binarySearch(v, low, mid - 1, x);
	return binarySearch(v, mid + 1, high, x);
}

int factorial(std::vector<int> &n_fives, int P) {

	int N = 0, size = n_fives.size(), current, cP, exponent;

	if (P == 0)
		return 1;

	while (P != 0) {
		current = binarySearch(n_fives, 0, size, P);

		exponent = (int) pow(5, current);
		cP = P / n_fives[current];

		if (cP == 5)
			return -1;

		N += exponent * cP;
		P %= n_fives[current];

		if (n_fives[current] - current + 1 <= P)
			return -1;
	}

	return N;
}

int main(void) {
	int N, P, i = 1;
	FILE *fin = fopen("fact.in", "r");
	fscanf(fin, "%d", &P);
	fclose(fin);

	std::vector<int> numberOf5s;

	numberOf5s.push_back(0);

	while (true) {
		numberOf5s.push_back(5 * numberOf5s[i - 1] + 1);
		if (numberOf5s[i] > PLIMIT)
			break;
		i++;
	}

	N = factorial(numberOf5s, P);

	FILE *fout = fopen("fact.out", "w");
	fprintf(fout, "%d", N);
	fclose(fout);

	return 0;
}