Search code examples
cmathmultiplication

Find the first number larger than M that results from continually multiplying 3 integers


Problem statement: Input: 4 integers M, x, y, z where 100,000 <= M <= 1,000,000 and -500 <= x, y, z <= 500. We want to continually multiply the squares of these numbers until we reach a number greater than M and print that number. For example, if M = 100,000 and x = 2, y = 3, z = 4, then

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

Here is my attempt:

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);
}

This works for a lot of inputs but gives the wrong answer for some edge cases. Unfortunately I don't have access to test data.

One issue could be overflow but my if statements should catch that.


Solution

  • You should use a proper loop for iteration. May be following code be useful:

     #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;
     }
    

    Also, for given input M = 100,000 and x = 2, y = 3, z = 4 then output should be

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