Cod sursa(job #2138097)

Utilizator fylot3Bogdan Filote fylot3 Data 21 februarie 2018 12:47:28
Problema Factorial Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.17 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;

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

		if (current < 0)
			return current;

		exponent = (int) std::pow(5, current);
		cP = P / n_fives[current];
		N += exponent * cP;
		P %= n_fives[current];

	}

	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;
}