Cod sursa(job #3251801)

Utilizator rst0605STAMULESCU ROBERT rst0605 Data 27 octombrie 2024 00:30:15
Problema Factorial Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.23 kb
#include <fstream>
#include <iostream>
#include <string>

using namespace std;

/*Sa se gaseasca cel mai mic numar natural strict pozitiv N 
pentru care N! are exact P cifre de 0 la sfarsit*/

int cnt(int n) {
    int count = 0;
    for (int i = 5; n / i >= 1; i *= 5) {
        count += n / i;
    }
    return count;
}

int main() {
	
	string localDir = "";    
	ifstream fin(localDir + "fact.in");
	ofstream fout(localDir + "fact.out");

    if (!fin.is_open()) {
        cerr << "Error: Could not open input file." << endl;
        return 1;
    }

    if (!fout.is_open()) {
        cerr << "Error: Could not open output file." << endl;
        return 1;
    }

   int P;
    fin >> P;

    if (P == 0) {
        fout << 1 << endl;
        return 0;
    }

    int low = 0, high = 5 * P, result = -1;

    while (low <= high) {
        int mid = (low + high) / 2;
        int zeros = cnt(mid);

        if (zeros == P) {
            result = mid;
            high = mid - 1; // Look for a smaller N
        } else if (zeros < P) {
            low = mid + 1;
        } else {
            high = mid - 1;
        }
    }

    fout << result << endl;

    fin.close();
    fout.close();
}