📜  计算n之前的平方数和非平方数

📅  最后修改于: 2021-04-30 03:40:38             🧑  作者: Mango

给定数字n,我们需要计算小于或等于n的平方数。
例子 :

Input : n = 5
Output : Square Number : 2
         Non-square numbers : 3
Explanation : Square numbers are 1 and 4.
Non square numbers are 2, 3 and 5.

Input : n = 10
Output : Square Number : 3
         Non-square numbers : 7
Explanation : Square numbers are 1, 4 and 9.
Non square numbers are 2, 3, 5, 6, 7, 8 and 10.

一个简单的解决方案是遍历从1到n的所有数字,并针对每个数字检查n是否为理想平方。
一个有效的解决方案基于以下公式。
大于0且小于或等于n的平方数的计数是floor(sqrt(n))或⌊√(n)⌋
非平方数的计数= n –⌊√(n)⌋

C++
// CPP program to count squares and
// non-squares before a number.
#include 
using namespace std;
 
void countSquaresNonSquares(int n)
{
    int sc = floor(sqrt(n));
    cout << "Count of squares "
         << sc << endl;
    cout << "Count of non-squares "
         << n - sc << endl;
}
 
// Driver Code
int main()
{
    int n = 10;
    countSquaresNonSquares(n);
    return 0;
}


Java
// Java program to count squares and
// non-squares before a number.
import java.io.*;
import java.math.*;
 
class GFG
{
    static void countSquaresNonSquares(int n)
    {
        int sc = (int)(Math.floor(Math.sqrt(n)));
        System.out.println("Count of" +
                     " squares " + sc);
        System.out.println("Count of" +
                      " non-squares " +
                            (n - sc) );
    }
 
    // Driver code
    public static void main(String args[])
    {
        int n = 10;
        countSquaresNonSquares(n);
    }
}
 
// This code is contributed
// by Nikita Tiwari.


Python3
# Python 3 program to count
# squares and non-squares
# before a number.
import math
 
def countSquaresNonSquares(n) :
    sc = (math.floor(math.sqrt(n)))
    print("Count of squares ", sc)
    print("Count of non-squares ", (n - sc) )
     
     
# Driver code
n = 10
countSquaresNonSquares(n)
 
# This code is contributed
# by Nikita Tiwari.


C#
// C# program to count squares and
// non-squares before a number.
using System;
 
class GFG
{
static void countSquaresNonSquares(int n)
{
    int sc = (int)Math.Sqrt(n);
    Console.WriteLine( "Count of " +
                        "squares " +
                               sc) ;
    Console.WriteLine("Count of " +
                   "non-squares " +
                         (n - sc));
}
 
    // Driver Code
    static public void Main ()
    {
    int n = 10;
    countSquaresNonSquares(n);
    }
}
 
// This code is contributed by anuj_67.


PHP


Javascript


输出 :

Count of squares 3
Count of non-squares 7