常见面试笔试编程题目

来源:互联网 发布:淘宝匿名买家提取器 编辑:程序博客网 时间:2024/06/11 23:47

【说明:以下题目均来自网络,答案为个人编写,仅供讨论,欢迎发表改进建议!】

 

 题目1:a^3 + b^3 + c^3 = d^3,a, b, c, d都是0999之间的整数,写代码找出所有符合该条件的a, b, c, d。

参考程序:以下程序在Linux上编译通过,共找出 3384 组答案,耗时约4秒

#include <iostream>#include <stdlib.h>#include <math.h>#define N 1000using namespace std;typedef unsigned int uint;typedef unsigned long long ullong;/* Store cubic values, data[n]=n^3 */ullong data[N] = {0};/* Get the cubic value of n */ullong cubic( uint n){    if(data[n] == 0)    {        data[n] = n*n*n;    }    return data[n];}int main(){    uint a,b,c,d;    ullong A,B,C,D;    double F;    for(d=0; d<N; d++)    {        D = cubic(d);        F = pow(D/3.0, 1.0/3);        for(a=(int)F; a<=d; a++)        {            A = cubic(a);            F = pow((D-A)/2.0, 1.0/3);            for(b=(int)F; b<=a; b++)            {                B = cubic(b);                if(A + B > D)                {                    break;                }                F = pow(D-A-B, 1.0/3);                for(c=(int)F; c<=b; c++)                {                    C = cubic(c);                    if( A + B + C == D )                    {                        cout<< a << "^3 + " << b << "^3 + " << c << "^3 == " << d << "^3" << "\t:\t";                        cout<< A << " + " << B << " + " << C << " == " << D << endl;                    }else if(A + B + C > D)                    {                        break;                    }                }            }        }    }    return 0;}