【发布时间】:2011-07-11 05:05:31
【问题描述】:
这是我对Problem 25 - Project Euler 的实现(请参阅代码中的 cmets 以了解其工作原理):
#include <iostream> //Declare headers and use correct namespace
#include <math.h>
using namespace std;
//Variables for the equation F_n(newTerm) = F_n-1(prevTerm) + Fn_2(currentTerm)
unsigned long long newTerm = 0;
unsigned long long prevTerm = 1; //F_1 initially = 1
unsigned long long currentTerm = 1; //F_2 initially = 2
unsigned long long termNo = 2; //Current number for the term
void getNextTerms() { //Iterates through the Fib sequence, by changing the global variables.
newTerm = prevTerm + currentTerm; //First run: newTerm = 2
unsigned long long temp = currentTerm; //temp = 1
currentTerm = newTerm; //currentTerm = 2
prevTerm = temp; //prevTerm = 1
termNo++; //termNo = 3
}
unsigned long long getLength(unsigned long long number) //Returns the length of the number
{
unsigned long long length = 0;
while (number >= 1) {
number = number / 10;
length++;
}
return length;
}
int main (int argc, const char * argv[])
{
while (true) {
getNextTerms(); //Gets next term in the Fib sequence
if (getLength(currentTerm) < 1000) { //Checks if the next terms size is less than the desired length
}
else { //Otherwise if it is perfect print out the term.
cout << termNo;
break;
}
}
}
这适用于示例,只要这一行就可以快速运行:
if (getLength(currentTerm) < 1000) { //Checks if the next term's size is less than the desired length
说 20 或更低,而不是 1000。但是如果这个数字大于 20,则需要很长时间,我的耐心变得更好,我停止了程序,我怎样才能使这个算法更有效?
如果您有任何问题,请在 cmets 中提问。
【问题讨论】:
-
128 位
unsigned long long的最大值类似于 3*10^38。这太小了,无法容纳千位数字。 -
@Mat:您对此有何建议?
-
一般来说,
long long将是 64 位 - 这种类型(如果它是无符号的)可以表示的最大数字是18446744073709551615,它有 20 位数字。没有办法用这种类型来表示一个有 1000 位数字的数字(这就是为什么它永远占用你的程序的原因——它无法完成)。要查找 1000 位的斐波那契数,您将无法仅使用long long类型 - 您需要以其他方式表示数字, -
对于 C bigint 库,请参阅 "'BigInt' in C?" 和 "What is the simplest way of implementing bigint in C?"
-
欧拉项目的目标是在寻找解决方案的同时获得乐趣,寻求帮助只会破坏乐趣恕我直言,对于您的问题,快速的方法是使用原生处理大量数字的python跨度>
标签: c++ performance