GESP Level 3 C++ Programming (49C++): How to Handle Triple Input for Multiples?

For the GESP Level 3 exam: GESP202406 Level 3 – Finding MultiplesThe difficulty of this problem lies in multi-layer input. Many candidates are familiar with one or two layers, but struggle with how to input three layers.Look at the problem:GESP Level 3 C++ Programming (49C++): How to Handle Triple Input for Multiples?GESP Level 3 C++ Programming (49C++): How to Handle Triple Input for Multiples?

Solution Approach:

1. First, we will record the input into an array. How to write for three layers?

#include <bits/stdc++.h>using namespace std;int main(){    int t;    cin >> t; // First layer input    for (int i = 0; i < t; i++)// t groups of data.    {        int n;        cin >> n;// Second layer input        int a[n];// Array length is n        for (int j = 0; j < n; j++)        {            int numb;            cin >> numb;// Third layer input            a[j] = numb;// Store n numbers in the array        }            }    return 0;}

2. The problem requires that the last number is a multiple of the previous numbers, which means the last number must be the largest. There are two solutions:

1. Find the maximum value and then check if it is a factor.

int maxnumb=0;maxnumb = max(a[i], maxa);string flg = "Yes";for (int j = n - 1; j >= 0; j--)      {               if (maxa% a[j] != 0)        {          flg = "No";          break;          }          }    cout << flg << endl;

2. Sort from smallest to largest and then check if it is a factor.

        sort(a, a + n);        string flg = "Yes";        for (int j = n - 1; j >= 0; j--)        {            if (a[n - 1] % a[j] != 0)            {                flg = "No";                break;            }        }        cout << flg << endl;

3. Complete code for sorting processing

#include <bits/stdc++.h>using namespace std;int main(){    int t;    cin >> t;    for (int i = 0; i < t; i++)    {        int n;        cin >> n;        int a[n];        for (int j = 0; j < n; j++)        {            int numb;            cin >> numb;            a[j] = numb;        }        sort(a, a + n);        string flg = "Yes";        for (int j = n - 1; j >= 0; j--)        {            if (a[n - 1] % a[j] != 0)            {                flg = "No";                break;            }        }        cout << flg << endl;    }    return 0;}

4. The logic for handling flg is not elaborated here. Reference:GESP Level 3 C++ Programming (45C++): Zeroing ArraysHave you learned it?GESP Level 3 C++ Programming (49C++): How to Handle Triple Input for Multiples?

Leave a Comment