给定数字n,找到模n下所有循环加性基团的生成器。集合{0,1,…n-1}的生成器是元素x,使得x小于n,并且使用x(和加法运算),我们可以生成集合中的所有元素。
例子:
Input : 10
Output : 1 3 7 9
The set to be generated is {0, 1, .. 9}
By adding 1, single or more times, we
can create all elements from 0 to 9.
Similarly using 3, we can generate all
elements.
30 % 10 = 0, 21 % 10 = 1, 12 % 10 = 2, ...
Same is true for 7 and 9.
Input : 24
Output : 1 5 7 11 13 17 19 23
一个简单的解决方案是运行一个从1到n-1的循环,并检查每个元素是否是生成器。为了检查生成器,我们不断添加元素,并检查是否可以生成所有数字,直到余数开始重复。
一种有效的解决方案基于以下事实:如果x相对于n质数,即gcd(n,x)= 1,则x是生成器。
下面是上述方法的实现:
C++
// A simple C++ program to find all generators
#include
using namespace std;
// Function to return gcd of a and b
int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b%a, a);
}
// Print generators of n
int printGenerators(unsigned int n)
{
// 1 is always a generator
cout << "1 ";
for (int i=2; i < n; i++)
// A number x is generator of GCD is 1
if (gcd(i, n) == 1)
cout << i << " ";
}
// Driver program to test above function
int main()
{
int n = 10;
printGenerators(n);
return 0;
}
Java
// A simple Java program to find all generators
class GFG {
// Function to return gcd of a and b
static int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b%a, a);
}
// Print generators of n
static void printGenerators(int n)
{
// 1 is always a generator
System.out.println("1 ");
for (int i=2; i < n; i++)
// A number x is generator of GCD is 1
if (gcd(i, n) == 1)
System.out.println(i +" ");
}
// Driver program to test above function
public static void main(String args[])
{
int n = 10;
printGenerators(n);
}
}
Python3
# Python3 program to find all generators
# Function to return gcd of a and b
def gcd(a, b):
if (a == 0):
return b;
return gcd(b % a, a);
# Print generators of n
def printGenerators(n):
# 1 is always a generator
print("1", end = " ");
for i in range(2, n):
# A number x is generator
# of GCD is 1
if (gcd(i, n) == 1):
print(i, end = " ");
# Driver Code
n = 10;
printGenerators(n);
# This code is contributed by mits
C#
// A simple C# program to find all generators
using System;
class GFG
{
// Function to return gcd of a and b
static int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
// Print generators of n
static void printGenerators(int n)
{
// 1 is always a generator
Console.Write("1 ");
for (int i = 2; i < n; i++)
// A number x is generator of GCD is 1
if (gcd(i, n) == 1)
Console.Write(i +" ");
}
// Driver code
public static void Main(String []args)
{
int n = 10;
printGenerators(n);
}
}
// This code contributed by Rajput-Ji
PHP
Javascript
输出 :
1 3 7 9