Editorial for Tính chẵn/lẻ


Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.

Submitting an official solution before solving the problem yourself is a bannable offence.

Spoiler Alert


Approach 1

  • Xét tính chia hết cho 2

\(n\) lẻ \(\Leftrightarrow n \equiv 1 \pmod{2} \Leftrightarrow n \mod{2} = 1\)

\(n\) chẵn \(\Leftrightarrow n \equiv 0 \pmod{2} \Leftrightarrow n \mod{2} = 0\)


Approach 2

  • Xét bit cuối của \(x\)

\(n = \Sigma_{i=0}^{\lfloor log_2{n} \rfloor} (x_i \times 2^i)\) với \(x_i \in \{0, 1\}\)

Khi \(\ last\_bit(n) = n\ \& \ 1 = 1\) có:

\(n = 1 + \Sigma_{i\ =\ 1}^{\lfloor log_2{n} \rfloor} (x_i \times 2^i)\) (\(x_i \in \{0, 1\}\), \(x_0 = 1\))

\(= 1 + 2 * \Sigma_{i\ =\ 0}^{\lfloor log_2{n} - 1 \rfloor} (x_i \times 2^i)\)

\(= 1 + 2 * k\) với \((k \in ℕ)\) là số lẻ

Khi \(\ last\_bit(n) = n\ \& \ 1 = 0\) có:

\(n = 0 + \Sigma_{i\ =\ 1}^{\lfloor log_2{n} \rfloor} (x_i \times 2^i)\) (\(x_i \in \{0, 1\}\), \(x_0 = 0\))

\(= 0 + 2 * \Sigma_{i\ =\ 0}^{\lfloor log_2{n} - 1 \rfloor} (x_i \times 2^i)\)

\(= 0 + 2 * k\) với \((k \in ℕ)\) là số chẵn


Approach 3

  • Xét chữ số cuối cùng của số biểu diễn dưới dạng xâu

Với \(s\)\(n\) biểu diễn dưới dạng xâu

\(n \equiv n \mod{10} \pmod{2}\)\(n \mod{10} = int(s.back() -\) '0') nên ta có

Khi \(\ last_digit(n) = n \mod 10 \in\) { 1, 3, 5, 7, 9} thì \(n\) lẻ

\(\Leftrightarrow s.back() \in\) {'1', '3', '5', '7', '9'}

Khi \(\ last_digit(n) = n \mod 10 \in\) {0, 2, 4, 6, 8} thì \(n\) chẵn

\(\Leftrightarrow s.back() \in\) {'0', '2', '4', '6', '8'}



Comments

There are no comments at the moment.