Skip to content

Instantly share code, notes, and snippets.

@WindAzure
Last active September 16, 2018 16:22
Show Gist options
  • Save WindAzure/d251a236b465ac42812e0da954c1bb57 to your computer and use it in GitHub Desktop.
Save WindAzure/d251a236b465ac42812e0da954c1bb57 to your computer and use it in GitHub Desktop.
UVa 11809
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <sstream>
#include <iostream>
#include <vector>
#define MAX_A_DIGIT 10
#define MAX_A_DIGIT_POWER_2 1024
#define TOLERANCE 0.00001
using namespace std;
struct MappingPair {
double decimalFractionNumber;
int binaryDigits;
};
vector<MappingPair> decimalFractionMappingTable;
void MakeTable()
{
int base2WeightTable[MAX_A_DIGIT] = { 512,256,128,64,32,16,8,4,2,1 };
for (auto i = 1; i < MAX_A_DIGIT_POWER_2; i++)
{
auto number = i;
auto position = 0;
while (number > 0)
{
if (number >= base2WeightTable[position])
{
number -= base2WeightTable[position];
}
position++;
}
auto mappingPair = MappingPair{ log10(1.0 * i / MAX_A_DIGIT_POWER_2), position };
decimalFractionMappingTable.push_back(mappingPair);
}
}
bool InputData(double &A, int &B)
{
auto numberStr = string{};
if (!(cin >> numberStr))
{
return false;
}
auto index = numberStr.find('e');
auto strA = numberStr.substr(0, index);
auto strB = numberStr.substr(index + 1, numberStr.size() - index);
stringstream(strA) >> A;
stringstream(strB) >> B;
return !(numberStr[0] == '0' && B == 0);
}
int CalculateTotalDigitsInBinary(int decimalNumber)
{
return (int)(log2(decimalNumber)) + 1;
}
double CalculateDecimalFractionNumber(double A, int B, int twoToThePowerE)
{
return log10(A) + B - log10(2.0)*twoToThePowerE;
}
double Calculate2ToPowerE(double A, int B)
{
return (int)(log2(A) + log2(10.0)*abs(B)) + 1;
}
int FindMinimumBinaryDigitsGreaterThan(double fractionNumber)
{
if (fabs(fractionNumber) <= TOLERANCE)
{
return 0.0;
}
for (auto index = 0; index < decimalFractionMappingTable.size(); index++)
{
auto difference = fabs(decimalFractionMappingTable[index].decimalFractionNumber - fractionNumber);
if (difference <= TOLERANCE || decimalFractionMappingTable[index].decimalFractionNumber >= fractionNumber)
{
return decimalFractionMappingTable[index].binaryDigits - 1;
}
}
return MAX_A_DIGIT;
}
int main()
{
MakeTable();
while (true)
{
auto A = 0.0;
auto B = 0;
if (!InputData(A, B))
{
break;
}
auto twoToThePowerE = Calculate2ToPowerE(A, B); //2^E
auto fractionNumber = CalculateDecimalFractionNumber(A, abs(B), twoToThePowerE);
auto M = FindMinimumBinaryDigitsGreaterThan(fractionNumber);
auto E = CalculateTotalDigitsInBinary(twoToThePowerE);
printf("%d %d\n", M, E);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment