找到第一个大于M的数字,它是连续乘以3个整数

时间:2017-06-03 06:33:23

标签: c math multiplication

问题陈述:输入:4个整数M,x,y,z其中100,000 <= M <= 1,000,000-500 <= x, y, z <= 500。我们希望不断地将这些数字的平方乘以我们达到大于M的数字并打印该数字。例如,如果M = 100,000且x = 2,则y = 3,z = 4,则

2^2 * 3^2 * 4^2 * 2^2 * 3^2 * 4^2 = 331,776

这是我的尝试:

int M, x, y, z, xs, ys, zs, prod_square;
scanf("%d%d%d%d", &M, &x, &y, &z);
if (x == 1 && y == 1 && z == 1) {
    printf("Poor input!\n");
    return 0;
}
if (x == 0 || y == 0 || z == 0) {
    printf("Poor input!\n");
    return 0;
}

xs = x*x; ys = y*y; zs = z*z;

if (xs > M) printf("%d\n", xs);

else if (xs*ys > M) printf("%d\n", xs*ys);

else if (xs*ys*zs > M) printf("%d\n", xs*ys*zs);

else {
    prod_square = xs*ys*zs;
    double temp = (log(M))/(log(prod_square));
    int n = (int)temp;
    int result = pow(prod_square, n);

    int try1 = result * xs;
    int try2 = result * xs * ys;

    if (try1 > M) printf("%d\n", try1);
    else if (try2 > M) printf("%d\n", try2);
}

这适用于大量输入但是对于某些边缘情况给出了错误的答案。不幸的是,我无法访问测试数据。

一个问题可能是溢出但我的if语句应该抓住它。

2 个答案:

答案 0 :(得分:3)

您应该使用适当的循环进行迭代。可能是以下代码有用:

 #include <stdio.h>

 int main()
 {
     int M, x, y, z, prod_square;
     scanf("%d%d%d%d", &M, &x, &y, &z);
     if (x == 1 && y == 1 && z == 1)
     {
         printf("Poor input!\n");
         return 0;
     }
     if (x == 0 || y == 0 || z == 0)
     {
         printf("Poor input!\n");
         return 0;
     }

     //Now code changes
     int result=1, indx =0, vals[3];
     vals[0] = x*x;
     vals[1] = y*y;
     vals[2] = z*z;

     while(result < M)
     {
         result *= vals[indx++];
         indx %=3;
     }
     printf("%d\n", result);
    return 0;
 }

此外,对于给定的输入M = 100,000x = 2, y = 3, z = 4,输出应为

2^2 * 3^2 * 4^2 * 2^2 * 3^2 * 4^2 = 331,776

答案 1 :(得分:-1)

我正在从此开始拍摄,但我相当确定当你从double投射到int时,它会向零截断。对于您的测试用例100,000 2,3,4,您会发现n在您的日志,除法和转换为int之后的值为1。当您致电pow(prod_square, n)时,您会回来prod_square因此,在此代码中,您需要考虑再次将所有三个值相乘的可能性 -

else {
    prod_square = xs*ys*zs;
    double temp = (log(M))/(log(prod_square));
    int n = (int)temp; // This will truncate towards 0
    int result = pow(prod_square, n);

    int try1 = result * xs;
    int try2 = result * xs * ys;

    if (try1 > M) printf("%d\n", try1);
    else if (try2 > M) printf("%d\n", try2);
    else printf("%d\n", result * prod_square);
}