给定一个整数N ,任务是找到总的不同余数的计数,当N被范围[1,N]中的每个元素除时可以得到。
例子:
Input: N = 5
Output: 3
5 % 1 = 0
5 % 2 = 1
5 % 3 = 2
5 % 4 = 1
5 % 5 = 0
The distinct remainders are 0, 1 and 2.
Input: N = 44
Output: 22
方法:可以很容易地观察到,对于N的偶数,不同的余数为N / 2 ,对于N的奇数,其为1 +⌊N/2⌋ 。
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
// Function to return the count of distinct
// remainders that can be obtained when
// n is divided by every element
// from the range [1, n]
int distinctRemainders(int n)
{
// If n is even
if (n % 2 == 0)
return (n / 2);
// If n is odd
return (1 + (n / 2));
}
// Driver code
int main()
{
int n = 5;
cout << distinctRemainders(n);
return 0;
}
Java
// Java implementation of the above approach
class GFG
{
// Function to return the count of distinct
// remainders that can be obtained when
// n is divided by every element
// from the range [1, n]
static int distinctRemainders(int n)
{
// If n is even
if (n % 2 == 0)
return (n / 2);
// If n is odd
return (1 + (n / 2));
}
// Driver code
public static void main(String[] args)
{
int n = 5;
System.out.println(distinctRemainders(n));
}
}
// This code is contributed by Mohit Kumar
Python3
# Python3 implementation of the approach
# Function to return the count of distinct
# remainders that can be obtained when
# n is divided by every element
# from the range [1, n]
def distinctRemainders(n):
# If n is even
if n % 2 == 0:
return n//2
# If n is odd
return ((n//2)+1)
# Driver code
if __name__=="__main__":
n = 5
print(distinctRemainders(n))
C#
// C# implementation of the above approach
using System;
class GFG
{
// Function to return the count of distinct
// remainders that can be obtained when
// n is divided by every element
// from the range [1, n]
static int distinctRemainders(int n)
{
// If n is even
if (n % 2 == 0)
return (n / 2);
// If n is odd
return (1 + (n / 2));
}
// Driver code
public static void Main()
{
int n = 5;
Console.WriteLine(distinctRemainders(n));
}
}
// This code is contributed by AnkitRai01
输出:
3
时间复杂度: O(1)