📌  相关文章
📜  打印n个数字,使它们的和成为一个完美的平方

📅  最后修改于: 2021-05-04 16:39:33             🧑  作者: Mango

给定一个整数n ,任务是打印n个数字,以使它们的和成为一个完美的平方。
例子:

方法:n个奇数之和始终是一个完美的平方。因此,我们将输出前n个奇数作为输出。
下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
 
// Function to print n numbers such that
// their sum is a perfect square
void findNumbers(int n)
{
    int i = 1;
    while (i <= n) {
 
        // Print ith odd number
        cout << ((2 * i) - 1) << " ";
        i++;
    }
}
 
// Driver code
int main()
{
    int n = 3;
    findNumbers(n);
}


Java
// Java implementation of the approach
class GFG {
 
    // Function to print n numbers such that
    // their sum is a perfect square
    static void findNumbers(int n)
    {
        int i = 1;
        while (i <= n) {
 
            // Print ith odd number
            System.out.print(((2 * i) - 1) + " ");
            i++;
        }
    }
 
    // Driver code
    public static void main(String args[])
    {
        int n = 3;
        findNumbers(n);
    }
}


Python3
# Python3 implementation of the approach
 
# Function to print n numbers such that
# their sum is a perfect square
def findNumber(n):
    i = 1
    while i <= n:
 
        # Print ith odd number
        print((2 * i) - 1, end = " ")
        i += 1
 
# Driver code    
n = 3
findNumber(n)
 
# This code is contributed by Shrikant13


C#
// C# implementation of the approach
using System;
public class GFG {
 
    // Function to print n numbers such that
    // their sum is a perfect square
    public static void findNumbers(int n)
    {
        int i = 1;
        while (i <= n) {
 
            // Print ith odd number
            Console.Write(((2 * i) - 1) + " ");
            i++;
        }
    }
 
    // Driver code
    public static void Main(string[] args)
    {
        int n = 3;
        findNumbers(n);
    }
}
 
// This code is contributed by Shrikant13


PHP


Javascript


输出
1 3 5 

时间复杂度: O(N)

辅助空间: O(1)