Print n numbers such that their sum is a perfect square

Given n numbers, we need to find n numbers whose sum is a perfect square. The solution uses the first n odd numbers, as the sum of first n odd numbers is always n².

Input : 5
Output : 1 3 5 7 9
1+3+5+7+9=25 i.e (5)²

Syntax

for(i = 1; i <= n; i++) {
    printf("%d ", (2*i - 1));
}

Algorithm

START
   Step 1: Read the value of n
   Step 2: Initialize i to 1
   Step 3: Loop while i <= n
      Step 3.1 ? Print (2*i - 1)
      Step 3.2 ? Increment i by 1
   Step 4: End loop
STOP

Example

This program prints the first n odd numbers whose sum forms a perfect square −

#include <stdio.h>

int main() {
    int n = 5;
    int i = 1;
    int sum = 0;
    
    printf("First %d odd numbers: ", n);
    while(i <= n) {
        int oddNumber = (2 * i) - 1;
        printf("%d ", oddNumber);
        sum += oddNumber;
        i++;
    }
    
    printf("\nSum = %d", sum);
    printf("\nSquare root = %d", n);
    printf("\nVerification: %d² = %d<br>", n, n * n);
    
    return 0;
}

Output

First 5 odd numbers: 1 3 5 7 9 
Sum = 25
Square root = 5
Verification: 5² = 25

How It Works

The mathematical property used here is that the sum of first n odd numbers equals n². The formula for the kth odd number is (2k - 1), where k starts from 1.

  • For n = 3: 1 + 3 + 5 = 9 = 3²
  • For n = 4: 1 + 3 + 5 + 7 = 16 = 4²
  • For n = 5: 1 + 3 + 5 + 7 + 9 = 25 = 5²

Conclusion

This approach efficiently generates n numbers whose sum is a perfect square by using the first n odd numbers. The sum is guaranteed to be n², making it a reliable solution for the given problem.

Updated on: 2026-03-15T11:03:32+05:30

231 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements