给定一个数组A,其中包含从2到N的数字。对其进行了特殊的筛分。
筛分程序如下:
- 创建一个元素为2到N的连续整数的数组,并将数组中的每个元素标记为未标记。
- 让的整数Q = N和标记Q的所有适当的除数除Q本身在数组中。
- 找到未标记的小于Q的最大数字,并为其分配Q,然后从步骤2开始重复。如果没有更多未标记的元素,则停止。
筛选后查找未标记整数的数量。
例子:
Input : N = 5
Output : Number of unmarked elements = 3
Explanation : We create array A[] = { 2, 3, 4, 5 }.
2 is marked as it is a proper divisor of 4.
Input : N = 4
Output : Number of unmarked elements = 2
天真的方法:
一种基本方法是运行两个循环。外循环遍历整个数组,内循环遍历2 – Q,通过检查a [i]%Q = 0取消标记Q的所有适当除数。
时间复杂度: O(N ^ 2)
高效方法:
一个简单的观察表明,实际上无需在此处进行筛分,N的值将确定答案。
情况1:如果N为奇数,则未标记元素的数量将为(N / 2)+ 1。
情况2:如果N为偶数,则未标记元素的数量将为(N / 2)。
时间复杂度: O(1)
例子:
Input : N = 5
Output : 3
A[] = { 2, 3, 4, 5 }
Steps:
1.) Q = 5 : Mark All the proper divisors of Q, here no element is there so every element remains unmarked.
3.) Q = 4 : Mark all the proper divisors of Q. Here 2 gets marked and unmarked elements are {3, 4, 5}.
5.) Q = 3 :
6.) Now no further marking can be done so stop here
So number of unmarked elements are 3 i.e {3, 4, 5}
In case of ODD value of N result should be (N/2)+1 = (3/2)+1 = (5/2)+1 = 2+1= 3.
Input : N = 4
Output : 2
A[] = { 2, 3, 4 }
Steps:
1.) Q = 4 Mark all the proper divisors of Q. So here 2 gets marked and unmarked elements are {3, 4}
3.) Q = 3
4.) Now no further marking can be done so stop here
So number of unmarked element after sieving are {3, 4} = 2
In case of EVEN value of N result should be (N/2) = (4/2) = 2
C++
// C++ Program to determine the
// number of unmarked integers in
// a special sieve
#include
using namespace std;
int countUnmarked(int N)
{
if (N % 2 == 0)
return N/2;
else
return N/2 + 1;
}
// Driver Code
int main()
{
int N = 4;
cout << "Number of unmarked elements: "
<< countUnmarked(N) << endl;
return 0;
}
Java
// Java Program to determine
// the number of unmarked
// integers in a special sieve
import java.io.*;
class GFG
{
static int countUnmarked(int N)
{
if (N % 2 == 0)
return N / 2;
else
return N / 2 + 1;
}
// Driver Code
public static void main (String[] args)
{
int N = 4;
System.out.println("Number of unmarked " +
"elements: " +
countUnmarked(N));
}
}
// This code is contributed
// by anuj_67.
Python3
# Python3 Program to determine
# the number of unmarked
# integers in a special sieve
def countUnmarked(N):
if (N % 2 == 0):
return N / 2;
else:
return N / 2 + 1;
# Driver Code
N = 4;
print("Number of unmarked elements:",
int(countUnmarked(N)));
# This code is contributed
# by mits
C#
// C# Program to determine
// the number of unmarked
// integers in a special sieve
using System;
class GFG
{
static int countUnmarked(int N)
{
if (N % 2 == 0)
return N / 2;
else
return N / 2 + 1;
}
// Driver Code
public static void Main ()
{
int N = 4;
Console.WriteLine("Number of unmarked " +
"elements: " +
countUnmarked(N));
}
}
// This code is contributed
// by anuj_67.
PHP
Number of unmarked elements: 2