Open In App

Removing a number from array to make it Geometric Progression

Last Updated : 14 Jul, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array arr[] of N positive elements, the task is to find whether it is possible to convert this array into Geometric Progression (GP) by removing at-most one element. If yes, then find index of the number removing which converts the array into a geometric progression. 
Special Cases : 
1) If whole array is already in GP, then return any index. 
2) If it is not possible to convert array into GP, then print “Not possible”.

Examples: 

Input  : arr[] = [2, 4, 8, 24, 16, 32]
Output : 3
Number to remove is arr[3], i.e., 24
After removing 24 array will be [2, 4, 8, 16, 32] which 
is a GP with starting value 2 and common ratio 2.

Input  : arr[] = [2, 8, 30, 60]
Output : Not Possible

We can solve this problem by handling some special cases and then finding the pivot element, removing which makes array a GP. First we will check that our pivot element is first or second element, if not then the multiplier between them will be common ration of our GP, if yes then we found our solution. 
Once we get common ratio of GP, we can check array element with this ratio, if this ratio violates at some index, then we skip this element and check from next index whether it is a continuation of previous GP or not. 
In below code a method isGP is implemented which checks array to be GP after removing element at index ‘index’. This method is written for special case handling of first, second and last element. 

Please see below code for better understanding.

C++




// C++ program to find the element removing which
// complete array becomes a GP
#include <bits/stdc++.h>
using namespace std;
#define EPS 1e-6
 
//  Utility method to compare two double values
bool fEqual(double a, double b)
{
    return (abs(a - b) < EPS);
}
 
//  Utility method to check, after deleting arr[ignore],
//  remaining array is GP or not
bool isGP(double arr[], int N, int ignore)
{
    double last = -1;
    double ratio = -1;
 
    for (int i = 0; i < N; i++)
    {
        //  check ratio only if i is not ignore
        if (i != ignore)
        {
            //  last will be -1 first time
            if (last != -1)
            {
                //  ratio will be -1 at first time
                if (ratio == -1)
                    ratio = (double)arr[i] / last;
 
                //  if ratio is not constant return false
                else if (!fEqual(ratio, (double)arr[i] / last))
                    return false;
            }
            last = arr[i];
        }
    }
    return true;
}
 
//  method return value removing which array becomes GP
int makeGPbyRemovingOneElement(double arr[], int N)
{
    /*  solving special cases separately */
    //  Try removing first element
    if (isGP(arr, N, 0))
        return 0;
 
    //  Try removing second element
    if (isGP(arr, N, 1))
        return 1;
 
    //  Try removing last element
    if (isGP(arr, N, N-1))
        return (N-1);
 
    /*  now we know that first and second element will be
        part of our GP so getting constant ratio of our GP */
    double ratio = (double)arr[1]/arr[0];
    for (int i = 2; i < N; i++)
    {
        if (!fEqual(ratio, (double)arr[i]/arr[i-1]))
        {
             /* At this point, we know that elements from arr[0]
               to arr[i-1] are in GP. So arr[i] is the element
               removing which may make GP.  We check if removing
               arr[i] actually makes it GP or not. */
            return (isGP(arr+i-2, N-i+2, 2))? i : -1;
         }
    }
 
    return -1;
}
 
//  Driver code to test above method
int main()
{
    double arr[] = {2, 4, 8, 30, 16};
    int N = sizeof(arr) / sizeof(arr[0]);
 
    int index = makeGPbyRemovingOneElement(arr, N);
    if (index == -1)
        cout << "Not possible\n";
    else
        cout << "Remove " << arr[index]
             << " to get geometric progression\n";
 
    return 0;
}


Java




// Java program to find the element removing which
// complete array becomes a GP
import java.util.*;
 
class GFG {
 
    final static double EPS = (double) 1e-6;
 
    // Utility method to compare two double values
    static boolean fEqual(double a, double b) {
        return (Math.abs(a - b) < EPS);
    }
 
    // Utility method to check, after deleting arr[ignore],
    // remaining array is GP or not
    static boolean isGP(double[] arr, int N, int ignore) {
        double last = -1;
        double ratio = -1;
 
        for (int i = 0; i < N; i++) {
 
            // check ratio only if i is not ignore
            if (i != ignore) {
 
                // last will be -1 first time
                if (last != -1) {
 
                    // ratio will be -1 at first time
                    if (ratio == -1)
                        ratio = (double) arr[i] / last;
 
                    // if ratio is not constant return false
                    else if (!fEqual(ratio, (double) arr[i] / last))
                        return false;
                }
                last = arr[i];
            }
        }
        return true;
    }
 
    // method return value removing which array becomes GP
    static int makeGPbyRemovingOneElement(double[] arr, int N) {
 
        /* solving special cases separately */
        // Try removing first element
        if (isGP(arr, N, 0))
            return 0;
 
        // Try removing second element
        if (isGP(arr, N, 1))
            return 1;
 
        // Try removing last element
        if (isGP(arr, N, N - 1))
            return (N - 1);
 
        /*
        * now we know that first and second element will be
        * part of our GP so getting constant ratio of our GP
        */
        double ratio = (double) arr[1] / arr[0];
        for (int i = 2; i < N; i++) {
            if (!fEqual(ratio, (double) arr[i] / arr[i - 1])) {
                /*
                * At this podouble, we know that elements from arr[0]
                * to arr[i-1] are in GP. Soarr[i] is the element
                * removing which may make GP. We check if removing
                * arr[i] actually makes it GP or not.
                */
                double[] temp = new double[N - i + 2];
                int k = 0;
                for (int j = i - 2; j < N; j++) {
                    temp[k++] = arr[j];
                }
                return (isGP(temp, N - i + 2, 2)) ? i : -1;
            }
        }
 
        return -1;
    }
 
    // Driver Code
    public static void main(String[] args) {
 
        double arr[] = { 2, 4, 8, 30, 16 };
        int N = arr.length;
 
        int index = makeGPbyRemovingOneElement(arr, N);
        if (index == -1)
            System.out.println("Not possible");
        else
            System.out.println("Remove " + arr[index] +
                        " to get geometric progression");
    }
}
 
// This code is contributed by
// sanjeev2552


Python3




# Python program to find the element removing which
# complete array becomes a GP
 
EPS = 1e-7
 
# Utility method to compare two double values
def fEqual(a, b):
    return abs(a - b) < EPS
 
# Utility method to check, after deleting arr[ignore],
# remaining array is GP or not
def isGP(arr, N, ignore):
    last = -1
    ratio = -1
 
    for i in range(N):
 
        # check ratio only if i is not ignore
        if i != ignore:
 
            # last will be -1 first time
            if last != -1:
 
                # ratio will be -1 at first time
                if ratio == -1:
                    ratio = arr[i] / last
 
                    # if ratio is not constant return false
                else if not fEqual(ratio, arr[i] / last):
                    return False
            last = arr[i]
 
    return True
 
# Method return value removing which array becomes GP
def makeGPbyRemovingOneElement(arr, N):
 
    # Solving special cases separately
    # Try removing first element
    if isGP(arr, N, 0):
        return 0
 
    # Try removing second element
    if isGP(arr, N, 1):
        return 1
 
    # Try removing last element
    if isGP(arr, N, N - 1):
        return N - 1
 
    # now we know that first and second element will be
    # part of our GP so getting constant ratio of our GP
    ratio = arr[1] / arr[0]
 
    for i in range(2, N):
        if not fEqual(ratio, arr[i] / arr[i - 1]):
 
            # At this point, we know that elements from arr[0]
            # to arr[i-1] are in GP. So arr[i] is the element
            # removing which may make GP. We check if removing
            # arr[i] actually makes it GP or not.
            return i if isGP(arr[i - 2:], N - i + 2, 2) else -1
 
    return -1
 
# Driver Code
if __name__ == "__main__":
    arr = [2, 4, 8, 30, 16]
    N = len(arr)
 
    index = makeGPbyRemovingOneElement(arr, N)
 
    if index == -1:
        print("Not Possible")
    else:
        print("Remove %d to get geometric progression" % arr[index])
 
# This code is contributed by
# sanjeev2552


C#




// C# program to find the element
// removing which complete array
// becomes a GP
using System;
  
class GFG{
  
static double EPS = (double)1e-6;
 
// Utility method to compare two
// double values
static bool fEqual(double a, double b)
{
    return (Math.Abs(a - b) < EPS);
}
 
// Utility method to check, after
// deleting arr[ignore], remaining
// array is GP or not
static bool isGP(double[] arr, int N,
                               int ignore)
{
    double last = -1;
    double ratio = -1;
 
    for(int i = 0; i < N; i++)
    {
         
        // Check ratio only if i is not ignore
        if (i != ignore)
        {
             
            // last will be -1 first time
            if (last != -1)
            {
                 
                // ratio will be -1 at first time
                if (ratio == -1)
                    ratio = (double)arr[i] / last;
 
                // If ratio is not constant return false
                else if (!fEqual(ratio,
                        (double) arr[i] / last))
                    return false;
            }
            last = arr[i];
        }
    }
    return true;
}
 
// Method return value removing
// which array becomes GP
static int makeGPbyRemovingOneElement(double[] arr,
                                      int N)
{
     
    // Solving special cases separately
    // Try removing first element
    if (isGP(arr, N, 0))
        return 0;
 
    // Try removing second element
    if (isGP(arr, N, 1))
        return 1;
 
    // Try removing last element
    if (isGP(arr, N, N - 1))
        return (N - 1);
 
    // Now we know that first and second
    // element will be part of our GP so
    // getting constant ratio of our GP
    double ratio = (double) arr[1] / arr[0];
     
    for(int i = 2; i < N; i++)
    {
        if (!fEqual(ratio, (double)arr[i] /
                                   arr[i - 1]))
        {
             
            // At this podouble, we know that
            // elements from arr[0] to arr[i-1]
            // are in GP. Soarr[i] is the element
            // removing which may make GP. We check
            // if removing arr[i] actually makes
            // it GP or not.
            double[] temp = new double[N - i + 2];
            int k = 0;
            for(int j = i - 2; j < N; j++)
            {
                temp[k++] = arr[j];
            }
            return (isGP(temp, N - i + 2, 2)) ? i : -1;
        }
    }
    return -1;
}
 
// Driver Code
public static void Main(string[] args)
{
     
    double []arr = { 2, 4, 8, 30, 16 };
    int N = arr.Length;
 
    int index = makeGPbyRemovingOneElement(arr, N);
    if (index == -1)
        Console.Write("Not possible");
    else
        Console.Write("Remove " + arr[index] +
                      " to get geometric progression");
}
}
 
// This code is contributed by rutvik_56


Javascript




// JavaScript program to find the element removing which
// complete ar4ray becomes a GP
let EPS = 1e-5;
 
// Utility method to compare two double values
function fEqual(a, b)
{  
     
    return Math.abs(Math.fround(a)  - Math.fround(b)) < Math.fround(EPS);
}
 
// Utility method to check, after deleting arr[ignore],
// remaining array is GP or not
function isGP(arr, N, ignore)
{
    var last = -1, ratio = -1;
 
    for (var i = 0; i < N; i++)
    {
 
        // check ratio only if i is not ignore
        if (i != ignore)
        {
            // last will be -1 first time
            if (last != -1)
            {
                // ratio will be -1 at first time
                if (ratio == -1)
                    ratio = (arr[i] / last);
 
                // if ratio is not constant return false
                else if  (!(fEqual(ratio, arr[i] / last)))
                    return false;
            }
            last = arr[i];
        }
    }
 
    return true;
}
 
// Method return value removing which array becomes GP
function makeGPbyRemovingOneElement(arr, N)
{
    // Solving special cases separately
    // Try removing first element
    if (isGP(arr, N, 0))
        return 0;
 
    // Try removing second element
    if (isGP(arr, N, 1))
        return 1;
 
    // Try removing last element
    if (isGP(arr, N, N - 1))
        return N - 1;
 
    // now we know that first and second element will be
    // part of our GP so getting constant ratio of our GP
    var ratio = parseFloat(arr[1] / arr[0]);
 
    for (var i = 2; i < N; i++)
    {
        if  (!fEqual(ratio, arr[i] / arr[i - 1]))
        {
 
            // At this point, we know that elements from arr[0]
            // to arr[i-1] are in GP. So arr[i] is the element
            // removing which may make GP. We check if removing
            // arr[i] actually makes it GP or not.
            if (isGP(arr.slice(i - 2), N - i + 2, 2))
                return i
            return -1;
        }
    }
 
    return -1
}
 
 
//  Driver Code
 
let arr = [2, 4, 8, 30, 16];
let N = arr.length;
 
let index = makeGPbyRemovingOneElement(arr, N)
 
if (index == -1)
    console.log("Not Possible")
else
    console.log("Remove", arr[index], "to get geometric progression");
 
// This code is contributed by phasing17


Output: 

Remove 30 to get geometric progression

 



Similar Reads

Number of GP (Geometric Progression) subsequences of size 3
Given n elements and a ratio r, find the number of G.P. subsequences with length 3. A subsequence is considered GP with length 3 with ration r. Examples: Input : arr[] = {1, 1, 2, 2, 4} r = 2 Output : 4 Explanation: Any of the two 1s can be chosen as the first element, the second element can be any of the two 2s, and the third element of the subseq
18 min read
Minimum number of operations to convert a given sequence into a Geometric Progression
Given a sequence of N elements, only three operations can be performed on any element at most one time. The operations are: Add one to the element.Subtract one from the element.Leave the element unchanged. Perform any one of the operations on all elements in the array. The task is to find the minimum number of operations(addition and subtraction) t
14 min read
Minimum number of operations to convert a given sequence into a Geometric Progression | Set 2
Given an array arr[] consisting of N integers, the following three operations can be performed on any element one at a time: Add one to the element.Subtract one from the element.Leave the element unchanged.The task is to find the minimum cost required to convert it into a Geometric Progression and also find the common ratio. Note: Each addition and
13 min read
Find the missing number in Geometric Progression
Given an array that represents elements of geometric progression in order. One element is missing in the progression, find the missing number. It may be assumed that one term is always missing and the missing term is not first or last of series. Examples: Input : arr[] = {1, 3 , 27, 81} Output : 9 Input : arr[] = {4, 16, 64, 1024}; Output : 256 A S
7 min read
Find all triplets in a sorted array that forms Geometric Progression
Given a sorted array of distinct positive integers, print all triplets that forms Geometric Progression with integral common ratio.A geometric progression is a sequence of numbers where each term after the first is found by multiplying the previous one by a fixed, non-zero number called the common ratio. For example, the sequence 2, 6, 18, 54,... i
10 min read
Geometric Progression
A sequence of numbers is called a Geometric progression if the ratio of any two consecutive terms is always the same. In simple terms, A geometric series is a list of numbers where each number, or term, is found by multiplying the previous term by a common ratio r. The general form of Geometric Progression is: [caption width="800"]GP-series[/captio
6 min read
Check whether nodes of Binary Tree form Arithmetic, Geometric or Harmonic Progression
Given a binary tree, the task is to check whether the nodes in this tree form an arithmetic progression, geometric progression or harmonic progression.Examples: Input: 4 / \ 2 16 / \ / \ 1 8 64 32 Output: Geometric Progression Explanation: The nodes of the binary tree can be used to form a Geometric Progression as follows - {1, 2, 4, 8, 16, 32, 64}
17 min read
Sum of N-terms of geometric progression for larger values of N | Set 2 (Using recursion)
A Geometric series is a series with a constant ratio between successive terms. The first term of the series is denoted by a and the common ratio is denoted by r. The series looks like this:- [Tex]a, ar, ar^2, ar^3, ar^4,... [/Tex]The task is to find the sum of such a series, mod M. Examples: Input: a = 1, r = 2, N = 10000, M = 10000 Output: 8751 In
7 min read
Sum of elements of a Geometric Progression (GP) in a given range
Given a Geometric Progression series in arr[] and Q queries in the form of [L, R], where L is the left boundary of the range and R is the right boundary. The task is to find the sum of the Geometric Progression elements in the given range. Note: The range is 1-indexed and1 ? L, R ? N, where N is the size of arr.Examples: Input: arr[] = {2, 4, 8, 16
6 min read
Longest subarray forming a Geometric Progression (GP)
Given a sorted array arr[] consisting of distinct numbers, the task is to find the length of the longest subarray that forms a Geometric Progression. Examples: Input: arr[]={1, 2, 4, 7, 14, 28, 56, 89}Output: 4Explanation:The subarrays {1, 2, 4} and {7, 14, 28, 56} forms a GP.Since {7, 14, 28, 56} is the longest, the required output is 4. Input: ar
8 min read
Article Tags :
Practice Tags :