给定两个整数n和g ,任务是生成n个整数的递增序列,使得:
- 序列中所有元素的gcd为g 。
- 并且,所有元素的总和在所有可能的序列中最小。
例子:
Input: n = 6, g = 5
Output: 5 10 15 20 25 30
Input: n = 5, g = 3
Output: 3 6 9 12 15
方法:当序列由以下元素组成时,序列的总和将最小:
g,2 * g,3 * g,4 * g,…..,n * g 。
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
// Function to print the required sequence
void generateSequence(int n, int g)
{
for (int i = 1; i <= n; i++)
cout << i * g << " ";
}
// Driver Code
int main()
{
int n = 6, g = 5;
generateSequence(n, g);
return 0;
}
Java
// Java implementation of the approach
class GFG
{
// Function to print the required sequence
static void generateSequence(int n, int g)
{
for (int i = 1; i <= n; i++)
System.out.print(i * g + " ");;
}
// Driver Code
public static void main(String []args)
{
int n = 6, g = 5;
generateSequence(n, g);
}
}
// This code is contributed by Rituraj Jain
Python3
# Python3 implementation of the approach
# Function to print the required sequence
def generateSequence(n, g):
for i in range(1, n + 1):
print(i * g, end = " ")
# Driver Code
if __name__ == "__main__":
n, g = 6, 5
generateSequence(n, g)
# This code is contributed by Rituraj Jain
C#
// C# implementation of the approach
using System ;
class GFG
{
// Function to print the required sequence
static void generateSequence(int n, int g)
{
for (int i = 1; i <= n; i++)
Console.Write(i * g + " ");
}
// Driver Code
public static void Main()
{
int n = 6, g = 5;
generateSequence(n, g);
}
}
// This code is contributed by Ryuga
PHP
输出:
5 10 15 20 25 30