// Problem 26
// 13 September 2002
//
// A unit fraction contains 1 in the numerator. The decimal representation of the unit fractions with denominators 2 to 10 are given:
//
// 1/2 = 0.5
// 1/3 = 0.(3)
// 1/4 = 0.25
// 1/5 = 0.2
// 1/6 = 0.1(6)
// 1/7 = 0.(142857)
// 1/8 = 0.125
// 1/9 = 0.(1)
// 1/10 = 0.1
// Where 0.1(6) means 0.166666..., and has a 1-digit recurring cycle. It can be seen that 1/7 has a 6-digit recurring cycle.
//
// Find the value of d 1000 for which 1/d contains the longest recurring cycle in its decimal fraction part.
#include <iostream>
#include <windows.h>
#include <vector>
using namespace std;
// 获取下一位小数,用remaindNum/num
// 余数保存在remaindNum中
int GetDivisor(int &remaindNum, int num)
{
remaindNum *= 10;
int result = remaindNum / num;
remaindNum = remaindNum % num;
return result;
}
vector<int> decimalNumVec; //保存小数位数
vector<int> remainderNumVec; //保存余数,位置与上面的保存小数的位置相同
// 检测是否成功获取到循环,如果余数和小数都相同,则表示找到了循环,返回循环位数
// 没有获取到循环返回0
int check(int inDecimalNum, int inRemainderNum)
{
int length = decimalNumVec.size();
for(int i = 0; i < length; i++)
{
if(inDecimalNum == decimalNumVec[i] && inRemainderNum == remainderNumVec[i])
{
return length - i - 1; //循环位数
}
}
return 0;
}
void F1()
{
cout << "void F1()" << endl;
LARGE_INTEGER timeStart, timeEnd, freq;
QueryPerformanceFrequency(&freq);
QueryPerformanceCounter(&timeStart);
const int MAX_NUM = 1000;
int decimalNum = 0, remaindNum = 0; //获取当前数的小数位和余数
int currentLength = 0; //获取当前数的小数循环长度
int maxLength = 0, maxNum = 0; //获取小数循环最长的长度和那个数
for(int i = 1; i <= MAX_NUM; i++)
{
decimalNumVec.clear();
remainderNumVec.clear();
remaindNum = 10; //初始化
while((currentLength = check(decimalNum, remaindNum)) == 0)
{
decimalNum = GetDivisor(remaindNum, i);
//记录小数位和余数
decimalNumVec.push_back(decimalNum);
remainderNumVec.push_back(remaindNum);
}
if(currentLength > maxLength)
{
maxLength = currentLength;
maxNum = i;
}
}
cout << "在1-" << MAX_NUM << "里,拥有最长循环小数单元的数是" << maxNum << ",1/" << maxNum << "是" << maxLength << "位循环小数" << endl;
QueryPerformanceCounter(&timeEnd);
cout << "Total Milliseconds is " << (double)((double)(timeEnd.QuadPart - timeStart.QuadPart) * 1000 / (double)freq.QuadPart) << endl;
}
//主函数
int main()
{
F1();
return 0;
}
/*
void F1()
在1-1000里,拥有最长循环小数单元的数是983,1/983是982位循环小数
Total Milliseconds is 2831.6
By GodMoon
*/
【ProjectEuler】ProjectEuler_026
最新推荐文章于 2024-12-31 10:07:21 发布
