The program segment given below prints four-digit special perfect square numbers in which the upper and lower two-digit numbers are perfect squares as well.
A for loop is set up such that the loop variable num assumes four-digit integer values (1000 to 9999). Within this loop, the :upper and lower two-digit numbers are first separated in variables upper and lower.Then the integer parts of the square roots of num, upper and lower are determined in variables nroot,uroot and lroot (all of type int),respectively. Subsequently, an if statement prints number num if it is a special perfect square number, i. e., if the numbers num,upper and lower are perfect squares. Observe the use of the logical AND ( &&) operator in the condition in the if statement.
Observe that the code given above is inefficient as it determines the upper and lower two-digit numbers and their square roots for each number num. Thus, the sqrt function, which is compute-intensive, is evaluated 27,000 times (9000 numbers x 3).
printf("Four digit special perfect square numbers: ");
for (num = 1000; num <= 9999; num++)
int nroot = (int) sqrt(num);
if (num == nroot * nroot) /* num is perfect square */
int upper = num / 100; /* upper 2 digit no. */
int uroot = sqrt(upper);
if (upper == uroot * uroot) /* upper is perfect square */
int lower = num % 100; /* lower 2 digit no. */
int lroot = sqrt(lower);
if (lower== lroot * lroot) /* lower is perfect square*/
printf("%d ", num);
The output of a program containing this code is given below. Four digit special perfect square numbers:
1600 1681 2500 3600 4900 6400 8100