C Exercise Example 3

100 Classic C Examples

Title:An integer: after adding 100, it is a perfect square, and after adding another 168, it is again a perfect square. What is this number?

Program analysis:

Suppose the number is x.

1. Then: x + 100 = n2, x + 100 + 168 = m2

2. Calculate the equation: m2 - n2 = (m + n)(m - n) = 168

3. Setup: m + n = i, m - n = j, i * j = 168, at least one of i and j is even

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

5. From the derivation in 3 and 4, it can be known that both i and j are even numbers greater than or equal to 2.

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

7. Next, simply loop through all numbers of i and calculate.

The specific 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

100 Classic C Examples

other extensions