Easy Tutorial
❮ C Exercise Example49 C Break Statement ❯

C Practice Example 3

C Language Classic 100 Examples

Question: An integer, when added to 100, becomes a perfect square, and when added to 268, becomes another perfect square. What is this number?

Program Analysis:

Assume the number is x.

  1. Then: x + 100 = n

  2. Calculate the equation: m

  3. Set: m + n = i, m - n = j, i * j = 168, i and j are at least one even number

  4. It follows: m = (i + j) / 2, n = (i - j) / 2, i and j are either both even or both odd.

  5. From steps 3 and 4, it can be deduced that i and j are both even numbers greater than or equal to 2.

  6. Since i * j = 168, j >= 2, then 1 < i < 168 / 2 + 1.

  7. Next, cycle through all possible values of i to find the solution.

The implementation is as follows:

Example

#include <stdio.h>

int main (void)
{
    int  i, j, m, n, x;
    for (i = 1; i < 168 / 2 + 1; i++)
    {
        if (168 % i == 0)
        {
            j = 168 / i;
            if ( i > j && (i + j) % 2 == 0 && (i - j) % 2 == 0)
            {
                m = (i + j) / 2;
                n = (i - j) / 2;
                x = n * n - 100;
                printf ("%d + 100 = %d * %d\n", x, n, n);
                printf ("%d + 268 = %d * %d\n", x, m, m);
            }
        }
    }
    return 0;
}

The output of the above example is:

-99 + 100 = 1 * 1
-99 + 268 = 13 * 13
21 + 100 = 11 * 11
21 + 268 = 17 * 17
261 + 100 = 19 * 19
261 + 268 = 23 * 23
1581 + 100 = 41 * 41
1581 + 268 = 43 * 43

C Language Classic 100 Examples

❮ C Exercise Example49 C Break Statement ❯