本文主要是介绍Project Euler 题解 #40 Champernowne's constant,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目:Champernowne's constant
An irrational decimal fraction is created by concatenating the positive integers:
0.123456789101112131415161718192021...
It can be seen that the 12th digit of the fractional part is 1.
If dn represents the nth digit of the fractional part, find the value of the following expression.
d1 d10d100d1000d10000d100000d1000000
这个题意是从特定的序列中获取特定的数字,重点在于从序列中分析出特点。解题思路
代码实现
//https://projecteuler.net/problem=40
//Champernowne's constant
#include <iostream>
#include <cmath>
using namespace std;
int GetNthDigit(unsigned int x, unsigned int N)
{
return N <= 0? 0 : (x/(int)pow(10.0, int(N - 1)))%10;
}
int D(unsigned int x)
{
unsigned int guard = 0;
int N = 0;
do
{
++N;
guard += 9 * N * (unsigned int)pow(10.0, int(N - 1));
} while (x > guard);
unsigned int offset = x - 1 - (guard - 9 * N * (unsigned int)pow(10.0, int(N - 1)));
unsigned int num = (unsigned int)pow(10.0, int(N - 1)) + offset/N;
unsigned int index = N - offset%N;
return GetNthDigit(num, index);
}
int _tmain(int argc, _TCHAR* argv[])
{
cout<<D(1)<<endl;
cout<<D(10)<<endl;
cout<<D(100)<<endl;
cout<<D(1000)<<endl;
cout<<D(10000)<<endl;
cout<<D(100000)<<endl;
cout<<D(1000000)<<endl;
system("pause");
return 0;
}
连乘可得210。
这篇关于Project Euler 题解 #40 Champernowne's constant的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!