Increasing sequence with given GCD
Last Updated :
23 Jun, 2022
Given two integers n and g, the task is to generate an increasing sequence of n integers such that:
- The gcd of all the elements of the sequence is g.
- And, the sum of all the elements is the minimum among all possible sequences.
Examples:
Input: n = 6, g = 5
Output: 5 10 15 20 25 30
Input: n = 5, g = 3
Output: 3 6 9 12 15
Approach: The sum of the sequence will be minimum when the sequence will consist of the elements:
g, 2 * g, 3 * g, 4 * g, ….., n * g.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void generateSequence( int n, int g)
{
for ( int i = 1; i <= n; i++)
cout << i * g << " " ;
}
int main()
{
int n = 6, g = 5;
generateSequence(n, g);
return 0;
}
|
Java
class GFG
{
static void generateSequence( int n, int g)
{
for ( int i = 1 ; i <= n; i++)
System.out.print(i * g + " " );;
}
public static void main(String []args)
{
int n = 6 , g = 5 ;
generateSequence(n, g);
}
}
|
Python3
def generateSequence(n, g):
for i in range ( 1 , n + 1 ):
print (i * g, end = " " )
if __name__ = = "__main__" :
n, g = 6 , 5
generateSequence(n, g)
|
C#
using System ;
class GFG
{
static void generateSequence( int n, int g)
{
for ( int i = 1; i <= n; i++)
Console.Write(i * g + " " );
}
public static void Main()
{
int n = 6, g = 5;
generateSequence(n, g);
}
}
|
PHP
<?php
function generateSequence( $n , $g )
{
for ( $i = 1; $i <= $n ; $i ++)
echo $i * $g . " " ;
}
$n = 6;
$g = 5;
generateSequence( $n , $g );
?>
|
Javascript
<script>
function generateSequence(n, g)
{
for ( var i = 1; i <= n; i++)
{
document.write(i*g+ " " );
}
}
var n = 6, g = 5;
generateSequence(n, g);
</script>
|
Time Complexity: O(n)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...