Find Content of a Polynomial from its integer coefficients
Given an array arr[] which denotes the integer coefficients of the polynomial, the task is to find the content of the polynomial.
Content of polynomials with integer coefficients is defined as the greatest common divisor of its integer coefficients.
That is for:
F(x) = amxm + am-1xm-1 + ……..+a1x + a0
Then, Content of Polynomial = gcd(am, am-1, am-2…., a1, a0)
Examples:
Input: arr[] = {9, 30, 12}
Output: 3
Explanation:
Given Polynomial can be: 9x2 + 30x + 12
Therefore, Content = gcd(9, 30, 12) = 3
Input: arr[] = {2, 4, 6}
Output: 2
Approach: The idea is to find the Greatest common divisor of all the elements of the array which can be computed by finding the GCD repeatedly by choosing two elements at a time. That is:
gcd(a, b, c)
= gcd(gcd(a, b), c)
= gcd(a, gcd(b, c))
= gcd(gcd(a, c), b)
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
#define newl "\n"
#define ll long long
#define pb push_back
int findContent( int arr[], int n)
{
int content = arr[0];
for ( int i = 1; i < n; i++) {
content = __gcd(content, arr[i]);
}
return content;
}
int main()
{
int n = 3;
int arr[] = { 9, 6, 12 };
cout << findContent(arr, n);
return 0;
}
|
Java
class GFG{
static int findContent( int arr[], int n)
{
int content = arr[ 0 ];
for ( int i = 1 ; i < n; i++)
{
content = __gcd(content, arr[i]);
}
return content;
}
static int __gcd( int a, int b)
{
return b == 0 ? a : __gcd(b, a % b);
}
public static void main(String[] args)
{
int n = 3 ;
int arr[] = { 9 , 6 , 12 };
System.out.print(findContent(arr, n));
}
}
|
Python3
from math import gcd
def findContent(arr, n):
content = arr[ 0 ]
for i in range ( 1 , n):
content = gcd(content, arr[i])
return content
if __name__ = = '__main__' :
n = 3
arr = [ 9 , 6 , 12 ]
print (findContent(arr, n))
|
C#
using System;
class GFG{
static int findContent( int []arr, int n)
{
int content = arr[0];
for ( int i = 1; i < n; i++)
{
content = __gcd(content, arr[i]);
}
return content;
}
static int __gcd( int a, int b)
{
return b == 0 ? a : __gcd(b, a % b);
}
public static void Main(String[] args)
{
int n = 3;
int []arr = { 9, 6, 12 };
Console.Write(findContent(arr, n));
}
}
|
Javascript
<script>
function findContent(arr, n)
{
var content = arr[0];
for ( var i = 1; i < n; i++)
{
content = __gcd(content, arr[i]);
}
return content;
}
function __gcd(a, b)
{
return b == 0 ? a : __gcd(b, a % b);
}
var n = 3;
var arr = [ 9, 6, 12 ];
document.write(findContent(arr, n));
</script>
|
Time Complexity: O(n*log(Ai))
Auxiliary Space: O(1)
Last Updated :
13 Oct, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...