给定整数n 。任务是计算将n减少为0所需的操作数。在每个操作中, n都可以更新为n = n – d ,其中d是n的最小素数。
例子:
Input: n = 5
Output: 1
5 is the smallest prime divisor, thus it gets subtracted and n gets reduced to 0.
Input: n = 25
Output: 11
5 is the smallest prime divisor, thus it gets subtracted and n gets reduced to 20. Then 2 is the smallest divisor and so on.
Input: n = 4
Output: 2
方法:
- 当n为偶数,则n的最小素除数为2和从n个减去2将再次给偶整数即获得2将被选择作为最小素除数并且这些步骤将重复,直到n变减少到0。
- 当n为奇数时,则n的最小素因子也将是奇数和从另一奇整数减去奇整数会给偶整数作为结果,然后将结果可通过重复当前偶数步骤1被发现。
- 因此,任务是找到最小的除数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
时间复杂度: