C Exercise 3
100 Classic C Language Examples
**Problem:** An integer, when increased by 100 becomes a perfect square, and when increased by another 168 becomes a perfect square again. What is this number?
Program analysis:
Assume the number is x.
1. Then: x + 100 = n2, x + 100 + 168 = m2
2. Compute the equation: m2 - n2 = (m + n)(m - n) = 168
3. Set: m + n = i, m - n = j, i * j = 168, at least one of i and j is even
4. We get: m = (i + j) / 2, n = (i - j) / 2; i and j are either both even or both odd.
5. From 3 and 4 we can deduce that both i and j are even numbers greater than or equal to 2.
6. Since i * j = 168 and j >= 2, then 1 < i < 168 / 2 + 1.
7. Next, just loop through all possible values of i to compute.
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