EularProject 44:和与差均是五角数中差最小值

来源:互联网 发布:移动4g网络类型是什么 编辑:程序博客网 时间:2024/05/03 20:30

Pentagon numbers
Problem 44
Pentagonal numbers are generated by the formula, Pn=n(3n−1)/2. The first ten pentagonal numbers are:

1, 5, 12, 22, 35, 51, 70, 92, 117, 145, …

It can be seen that P4 + P7 = 22 + 70 = 92 = P8. However, their difference, 70 − 22 = 48, is not pentagonal.

Find the pair of pentagonal numbers, Pj and Pk, for which their sum and difference are pentagonal and D = |Pk − Pj| is minimised; what is the value of D?

Answer:
5482660
Completed on Tue, 25 Aug 2015, 04:45
Go to the thread for problem 44 in the forum.

#include<iostream>#include<math.h># define maxStep 10000using namespace std;long func(long n){    return n*(3 * n - 1) / 2;}bool IsPentagonal(long x){    long temp = ceil(sqrt(2.0*x / 3));    return (2 * x == 3 * temp*temp - temp) ? true : false;}bool Stop(long start, long step){    long high = func(start);    long little = func(start - step);    long sum = little + high;    if (IsPentagonal(sum) == false)        return false;    long diff = high - little;    if (IsPentagonal(diff)==false)        return false;    return diff;}void main(){    long base = func(1);    long lst[maxStep], start[maxStep], step[maxStep];    for (int i = 0; i < maxStep; i++)    {        lst[i] = func(i + 2) - base;        start[i] = i + 2;        step[i] = i + 1;    }    while (true)    {        long result = Stop(start[0], step[0]);        if (result)        {            cout << start[0] <<"  "<< step[0] << endl;            cout << func(start[0])-func(start[0]-step[0]) << endl;            system("pause");        }        start[0]++;        long s1 = start[0];        long s2 = step[0];        lst[0] = func(s1) - func(s1 - s2);        {            long k = 1;            long lst_temp = lst[0];            long start_temp = start[0];            long step_temp = step[0];            while (lst_temp > lst[k])            {                lst[k-1] = lst[k];                start[k-1] = start[k];                step[k-1] = step[k];                k++;                if (k == maxStep)                {                    cout << "程序退出,因为需要增加maxStep" << endl;                    return;                }            }            lst[k - 1] = lst_temp;            start[k - 1] = start_temp;            step[k - 1] = step_temp;        }    }    system("pause");}
0 0
原创粉丝点击