Basic Problem Solving Tips
--i
when erase()
element inside loop
if
erase()
an element inside a for or while loop, we must do--i
i.e. decreasei
to the prevous index as the size() of container became 1 less.
for (int i = 0; i < v.size() - 1; i++) {
v.erase(v.begin() + (i + 1));
--i;
}
gcd
tricks
use
__gcd(a, b)
orgcd(a, b)
from<numeric>
C++ STL
caution
gcd(a, b) == 1
whena
andb
are consecutive numbers ie. b = a+1 or a = b+1
for
n
is ODD,x
is ODD,gcd(a, b) == 2
gcd(n - x, n + x) == 2
whena
andb
are equally separated = ODDx
from the middle elementn
; gcd is2
for
n
is ODD,x
is EVEN,gcd(a, b) == 1
gcd(n - x, n + x) == 1
whena
andb
are equally separated = EVENx
from the middle elementn
; gcd is1
for
n
is EVEN,x
is ODD,gcd(a, b) == 1
gcd(n - x, n + x) == 1
whena
andb
are equally separated = ODDx
from the middle elementn
; gcd is1
for
n
is EVEN,x
is EVEN,gcd(a, b) == 2
gcd(n - x, n + x) == 2
whena
andb
are equally separated = EVENx
from the middle elementn
; gcd is2
gcd(a, a) == a
lcm
tricks
use
lcm(a, b)
from<numeric>
C++ STL
lcm(a, a) == a
gcd
and LCM
relation
info
[ lcm(a, b) * gcd(a, b) ] = [ a * b ]
⏬
lcm(a, b) = [ (a*b)/(gcd(a, b)) ]
