📌  相关文章
📜  减少N到0所需的给定类型的计数操作

📅  最后修改于: 2021-04-22 00:17:30             🧑  作者: Mango

给定整数n 。任务是计算将n减少为0所需的操作数。在每个操作中, n都可以更新为n = n – d ,其中dn的最小素数。

例子:

方法:

  1. n偶数,则n的最小素除数为2和从n个减去2将再次给偶整数即获得2将被选择作为最小素除数并且这些步骤将重复,直到n变减少到0。
  2. n奇数时,则n的最小素因子也将是奇数和从另一奇整数减去奇整数会给偶整数作为结果,然后将结果可通过重复当前偶数步骤1被发现。
  3. 因此,任务是找到最小的除数d ,将其减去n = n – d并打印1 +((n – d)/ 2)

下面是上述方法的实现:

C++
// C++ implementation of the approach
#include
using namespace std;
  
// Function to return the required 
// number of operations
int countOperations (int n)
{
    int i = 2;
      
    // Finding the smallest divisor
    while ((i * i) < n && (n % i))
        i += 1;
      
    if ((i * i) > n)
        i = n;
      
    // Return the count of operations
    return (1 + (n - i)/2);
}
  
// Driver code
int main()
{
    int n = 5;
    cout << countOperations(n);
}
  
//This code is contributed by Shivi_Aggarwal


Java
// Java implementation of the approach
class GFG
{
  
// Function to return the required 
// number of operations
static int countOperations (int n)
{
    int i = 2;
      
    // Finding the smallest divisor
    while ((i * i) < n && (n % i) > 0)
        i += 1;
      
    if ((i * i) > n)
        i = n;
      
    // Return the count of operations
    return (1 + (n - i) / 2);
}
  
// Driver code
public static void main(String[] args)
{
    int n = 5;
    System.out.println(countOperations(n));
}
}
  
// This code is contributed
// by Akanksha Rai


Python3
# Python3 implementation of the approach
  
# Function to return the required 
# number of operations
def countOperations(n):
    i = 2
      
    # Finding the smallest divisor
    while ((i * i) < n and (n % i)):
        i += 1
      
    if ((i * i) > n):
        i = n
      
    # Return the count of operations
    return (1 + (n - i)//2)
  
# Driver code
n = 5
print(countOperations(n))


C#
// C# implementation of the approach
using System;
class GFG
{
  
// Function to return the required 
// number of operations
static int countOperations (int n)
{
    int i = 2;
      
    // Finding the smallest divisor
    while ((i * i) < n && (n % i) > 0)
        i += 1;
      
    if ((i * i) > n)
        i = n;
      
    // Return the count of operations
    return (1 + (n - i) / 2);
}
  
// Driver code
static void Main()
{
    int n = 5;
    Console.WriteLine(countOperations(n));
}
}
  
// This code is contributed by mits


PHP
 $n) 
        $i = $n;
      
    # Return the count of operations 
    return 1 + floor(($n - $i) / 2);
}
  
// Driver code 
$n = 5 ;
echo countOperations($n); 
  
// This code is contributed by Ryuga
?>


输出:
1

时间复杂度: O(\sqrt{n})