660A - Co-prime Array - CodeForces Solution


greedy implementation math number theory *1200

Please click on ads to support us..

Python Code:

def gcd(a, b):
    while b != 0:
        a, b = b, a % b
    return a


def solution():
    n = int(input())
    vals = list(map(int, input().split()))
    if n == 1:
        print(0)
        print(*vals)
    else:
        i = 0
        c = 0
        while i < n-1:
            if gcd(vals[i], vals[i+1]) != 1:
                vals.insert(i+1, 1)
                n += 1
                c += 1
            i += 1
        print(c)
        print(*vals)


t = 1
while t:
    t -= 1
    solution()

	  			   		 							 	    				 	

C++ Code:

#include<bits/stdc++.h>
using namespace std;

#define ll long long

int main()
{
    ll n;
    cin>>n;
    vector<ll>a(n);
    for(ll i=0;i<n;i++)cin>>a[i];
    
    vector<ll>ans;
    ans.push_back(a[0]);
    
    for(ll i=1;i<n;i++){
        if(__gcd(a[i-1],a[i])!=1)
            ans.push_back(1);
        ans.push_back(a[i]);
    }
    cout<<ans.size()-n<<endl;
    for(auto num : ans)
    cout<<num<<" ";
    cout<<endl;
}


Comments

Submit
0 Comments
More Questions

873D - Merge Sort
1251A - Broken Keyboard
463B - Caisa and Pylons
584A - Olesya and Rodion
799A - Carrot Cakes
1569B - Chess Tournament
1047B - Cover Points
1381B - Unmerge
1256A - Payment Without Change
908B - New Year and Buggy Bot
979A - Pizza Pizza Pizza
731A - Night at the Museum
742A - Arpa’s hard exam and Mehrdad’s naive cheat
1492A - Three swimmers
1360E - Polygon
1517D - Explorer Space
1230B - Ania and Minimizing
1201A - Important Exam
676A - Nicholas and Permutation
431A - Black Square
474B - Worms
987B - High School Become Human
1223A - CME
1658B - Marin and Anti-coprime Permutation
14B - Young Photographer
143A - Help Vasilisa the Wise 2
320A - Magic Numbers
1658A - Marin and Photoshoot
514A - Chewbaсca and Number
382A - Ksenia and Pan Scales