📜  用重复减法计算数字的平方根

📅  最后修改于: 2021-05-06 09:00:00             🧑  作者: Mango

给定整数N ,任务是仅通过重复减法来找到其完美平方根。
例子:

巴比伦方法和二进制搜索方法:基于巴比伦方法和二进制搜索的方法请参考整数的平方根。
重复减法:
请按照以下步骤解决问题:

  • N个奇数自然数的总和等于N 2
  • 基于上述事实,需要对从1开始直到N变为0的奇数进行重复减法。
  • 在此过程中使用的奇数计数将得出数字N的平方根。

下面是上述方法的实现。

C++
// C++ implementation of
// the above approach
#include 
using namespace std;
 
// Function to return the square
// root of the given number
int SquareRoot(int num)
{
    int count = 0;
 
    for (int n = 1; n <= num; n += 2) {
 
        // Subtract n-th odd number
        num = num - n;
        count += 1;
        if (num == 0)
            break;
    }
 
    // Return the result
    return count;
}
 
// Driver Code
int main()
{
    int N = 81;
    cout << SquareRoot(N);
}


Java
// Java implementation of
// the above approach
class GFG{
     
// Function to return the square
// root of the given number
public static int SquareRoot(int num)
{
    int count = 0;
     
    for(int n = 1; n <= num; n += 2)
    {
 
       // Subtract n-th odd number
       num = num - n;
       count += 1;
       if (num == 0)
           break;
    }
     
    // Return the result
    return count;
}
 
// Driver code   
public static void main(String[] args)
{
    int N = 81;
    System.out.println(SquareRoot(N));
}
}
 
// This code is contributed by divyeshrabadiya07


Python3
# Python3 implementation of the
# above approach
 
# Function to return the square
# root of the given number
def SquareRoot(num):
     
    count = 0
    for n in range(1, num + 1, 2):
         
        # Subtract n-th odd number
        num = num - n
        count = count + 1
        if (num == 0):
            break
 
    # Return the result
    return count
 
# Driver Code
N = 81
print(SquareRoot(N))
 
# This code is contributed by Sanjit_Prasad


C#
// C# implementation of
// the above approach
using System;
 
class GFG{
     
// Function to return the square
// root of the given number
public static int SquareRoot(int num)
{
    int count = 0;
     
    for(int n = 1; n <= num; n += 2)
    {
         
        // Subtract n-th odd number
        num = num - n;
        count += 1;
        if (num == 0)
            break;
    }
     
    // Return the result
    return count;
}
 
// Driver code
public static void Main()
{
    int N = 81;
     
    Console.Write(SquareRoot(N));
}
}
 
// This code is contributed by chitranayal


Javascript


输出:
9

时间复杂度: O(N)
辅助空间: O(1)