This blog is under construction

Sunday, 23 June 2013

C program to print the numbers whose square of sum of first half and second half of the number results the same

Write a C program to print the four digit numbers whose square of sum of first half and second half of the number results the same.

Example: 2025
(20 + 25) ^ 2 = 2025


  #include <stdio.h>
  int main() {
        int num, fhalf = 10, shalf = 0, square;
        num = fhalf * 100 + shalf;
        printf("Result:\n");
        while (num < 9999) {
                /* 
                 * (a + b)^2 - formula.. where a is first
                 * half and b is second half of the given number
                 * num - starts from 1000 -> (10 + 00)^2
                 */
                square = (fhalf * fhalf) +
                                (shalf * shalf) + 2 * fhalf * shalf;
                num = fhalf * 100 + shalf;
                if (num == square)
                        printf("%d\n", num);
                if (shalf == 99) {
                        shalf = -1;
                        fhalf++;
                }
                shalf++;
        }
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Result:
  2025
  3025
  9801



No comments:

Post a Comment