Print n numbers such that their sum is a perfect square
Given an integer n, the task is to print n numbers such that their sum is a perfect square.
Examples:
Input: n = 3
Output: 1 3 5
1 + 3 + 5 = 9 = 32
Input: n = 4
Output: 1 3 5 7
1 + 3 + 5 + 7 = 16 = 42
Approach: The sum of first n odd numbers is always a perfect square. So, we will print the first n odd numbers as the output.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void findNumbers( int n)
{
int i = 1;
while (i <= n) {
cout << ((2 * i) - 1) << " " ;
i++;
}
}
int main()
{
int n = 3;
findNumbers(n);
}
|
Java
import java.util.*;
import java.io.*;
class GFG {
static void findNumbers( int n)
{
int i = 1 ;
while (i <= n) {
System.out.print((( 2 * i) - 1 ) + " " );
i++;
}
}
public static void main(String args[])
{
int n = 3 ;
findNumbers(n);
}
}
|
Python3
def findNumber(n):
i = 1
while i < = n:
print (( 2 * i) - 1 , end = " " )
i + = 1
n = 3
findNumber(n)
|
C#
using System;
public class GFG {
public static void findNumbers( int n)
{
int i = 1;
while (i <= n) {
Console.Write(((2 * i) - 1) + " " );
i++;
}
}
public static void Main( string [] args)
{
int n = 3;
findNumbers(n);
}
}
|
PHP
<?php
function findNumbers( $n )
{
$i = 1;
while ( $i <= $n )
{
echo ((2 * $i ) - 1) . " " ;
$i ++;
}
}
$n = 3;
findNumbers( $n );
?>
|
Javascript
<script>
function findNumbers(n)
{
var i = 1;
while (i <= n) {
document.write(((2 * i) - 1)+ " " ) ;
i++;
}
}
var n = 3;
findNumbers(n);
</script>
|
Time Complexity: O(N), as we are using a loop to traverse N times so it will cost us O(N) time.
Auxiliary Space: O(1), as we are not using any extra space.
Last Updated :
20 Dec, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...