Skip to main content

CSES PROBLEMSET

INTRODUCTORY PROBLEMS



1. WEIRD ALGORITHM

SOLUTION:

#include<bits/stdc++.h>
using namespace std ;
int main(){
long long n; //beacuse n can be greater than max size of int.
cin>>n;
while(n!=1){ // loop will break when n become 1.
cout << n << " ";
if(n&1)n = n *3+1; // when n is odd.
else n = n/2; // when n is even.
}
cout<< "1";
}



2. MISSING NUMBER

SOLUTION:

LOGIC: just sum all the inputs and subtract from total sum(n*(n+1)/2).

#include<bits/stdc++.h>
using namespace std;
int main(){
       long long n,s,sum=0;    
        cin>>n;
        for(long long i=0;i<n-1;i++){
           cin>>s;sum+=s; //sum all the inputs.
        }
        cout<<((n*(n+1))/2)-sum; // and subtracting from total sum.
}

Comments

Post a Comment