Given three integers A, B and N the task is to find N Arithmetic means between A and B. We basically need to insert N terms in an Arithmetic progression. where A and B are first and last terms. Examples:
Input : A = 20 B = 32 N = 5
Output : 22 24 26 28 30
The Arithmetic progression series as
20 22 24 26 28 30 32
Input : A = 5 B = 35 N = 5
Output : 10 15 20 25 30
Approach : Let A1, A2, A3, A4……An be N Arithmetic Means between two given numbers A and B . Then A, A1, A2 ….. An, B will be in Arithmetic Progression . Now B = (N+2)th term of the Arithmetic progression . So : Finding the (N+2)th term of the Arithmetic progression Series where d is the Common Difference B = A + (N + 2 – 1)d B – A = (N + 1)d So the Common Difference d is given by. d = (B – A) / (N + 1) So now we have the value of A and the value of the common difference(d), now we can find all the N Arithmetic Means between A and B.
C++
#include <bits/stdc++.h>
using namespace std;
void printAMeans( int A, int B, int N)
{
float d = ( float )(B - A) / (N + 1);
for ( int i = 1; i <= N; i++)
cout << (A + i * d) << " " ;
}
int main()
{
int A = 20, B = 32, N = 5;
printAMeans(A, B, N);
return 0;
}
|
Java
import java.io.*;
import java.lang.*;
import java.util.*;
public class GFG {
static void printAMeans( int A, int B, int N)
{
float d = ( float )(B - A) / (N + 1 );
for ( int i = 1 ; i <= N; i++)
System.out.print((A + i * d) + " " );
}
public static void main(String args[])
{
int A = 20 , B = 32 , N = 5 ;
printAMeans(A, B, N);
}
}
|
Python3
def printAMeans(A, B, N):
d = (B - A) / (N + 1 )
for i in range ( 1 , N + 1 ):
print ( int (A + i * d), end = " " )
A = 20 ; B = 32 ; N = 5
printAMeans(A, B, N)
|
C#
using System;
public class GFG {
static void printAMeans( int A, int B, int N)
{
float d = ( float )(B - A) / (N + 1);
for ( int i = 1; i <= N; i++)
Console.Write((A + i * d) + " " );
}
public static void Main()
{
int A = 20, B = 32, N = 5;
printAMeans(A, B, N);
}
}
|
PHP
<?php
function printAMeans( $A , $B , $N )
{
$d = ( $B - $A ) / ( $N + 1);
for ( $i = 1; $i <= $N ; $i ++)
echo ( $A + $i * $d ) , " " ;
}
$A = 20; $B = 32;
$N = 5;
printAMeans( $A , $B , $N );
?>
|
Javascript
<script>
function printAMeans(A, B, N){
let d = (B - A) / (N + 1)
for (let i = 1; i < N + 1; i++)
document.write(Math.floor(A + i * d), " " )
}
let A = 20, B = 32, N = 5;
printAMeans(A, B, N)
</script>
|
Time Complexity : O(N) ,where N is the number of terms
Space Complexity : O(1), since no extra space has been taken.
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
27 Aug, 2022
Like Article
Save Article