A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 ร 99.
Find the largest palindrome made from the product of two 3-digit numbers.
Korean: http://euler.synap.co.kr/prob_detail.php?id=4
English: https://projecteuler.net/problem=4
- Tool: Visual Studio Code
- Language: C
- Compiler: gcc.exe (MinGW.org GCC-6.3.0-1) 6.3.0
- Use MinGW
Change directory git root: /Problem4 and compile
gcc Problem4.cwith debugging https://gcc.gnu.org/onlinedocs/gcc/Debugging-Options.html#Debugging-Options
gcc -g Problem4.cWindows Environment Settings
System Variable > Path > Add "C:\MinGW\bin" (Installed path)
Run
a- Open folder "Problem4" by Visual Studio Code
- Check out settings: launch.json and tasks.json
- launch.json
- "miDebuggerPath": "C:/mingw/bin/gdb.exe"
- Use MinGW installed your path
- tasks.json
- Use gdb debug: args[0] = "-g"
- launch.json
- Press F5 to debug start
- Palindrome ๊ตฌํ๋ ์์ด๋์ด๋ ๋ค์๊ณผ ๊ฐ๋ค.
- ์ฃผ์ด์ง ์ซ์๋ฅผ ๋ฌธ์์ด๋ก ๋ณํ, sprintf
- ๊ทธ ๋ฌธ์์ด์ ๋ค์ง์ ๋ฌธ์์ด, strrev
- ์ฒซ ๋ฌธ์์ด๊ณผ reversed ๋ฌธ์์ด์ด ๊ฐ์ผ๋ฉด Palindrome ์ด๋ผ๊ณ ์๊ฐํด ๋ณผ ์ ์๋ค, strcmp
- IsPalindrome ํจ์๋ ์ ์ธ ์์ด๋์ด๋ฅผ ์ค์ ๋ก ๊ตฌํํ ํจ์์ด๋ค.
- ์ฃผ์ด์ง ์กฐ๊ฑด์ ์ธ์๋ฆฌ ์์ ๊ณฑ ์ค ์ต๋๊ฐ์ ๊ตฌํ๋ ๊ฒ์ด๋ฏ๋ก ์ธ์๋ฆฌ ์ ์ต๋๊ฐ์ธ 999 ๋ถํฐ ์์ํด์ loop๋ฌธ์ ์ญ์ผ๋ก ๋๋ ค ์ฐพ์๋ธ๋ค.
- ๋ค์ ์๊ฐํด ๋ณด๋ฉด 999 ~ 901 ๋ฒ์ ์์์ ๋ ์๋ฅผ ๊ณฑํ๋ฉด ๋ฐ๋์ Palindrome์ด ๋์ค๊ฒ ๋์ด ์์ผ๋ฏ๋ก for๋ฌธ์ ํํ๋ ๋ค์๊ณผ ๊ฐ๊ฒ ๋๋ค. for (int i=999; i>=900; i--)
- ์ด์ ๋ฅผ ์๊ฐํด ๋ณด๋ฉด 999 x 901์ 900,099 ์ด๋ฉฐ ๊ตฌ์ญ๋ง์ผ๋ก ์์ํ๋ ์ซ์ ๋ฒ์ ์ค ๊ฐ์ ์์ ์ซ์์ด๋ค.
- Palindrome ์์ ๋ฒ์๋ 999 x 999์ธ 998,001 ๋ถํฐ์ด๋ฏ๋ก ์ด ์ฌ์ด์ Palindrome์ด ์์ ๊ฒ์ด๋ผ ์์ธกํ ์ ์๋ค.
- ์ด๋ ๊ฒ ํด์ nested for loop์ ๋ง๋ค์ด ๊ฐ์ฅ ๋จผ์ IsPalindrome์ ๊ฑธ๋ฆฌ๋ ์๊ฐ ๋ํ๋๋ค๋ฉด ์ธ์๋ฆฌ ์์ ๊ณฑ ์ค ๊ฐ์ฅ ํฐ palindrome ๊ฐ์ด๋ผ๊ณ ํ๋จํ ์ ์๋ค.
- ์์ ์๋ ๋ชฐ๋๋๋ฐ ๋ฌธ์์ด์ ๋ค์ง์ด์ ์ถ๋ ฅํ๋ strrev ํจ์์ ์กด์ฌ๋ฅผ ์์๋ค. ์ ๊ธฐํ๊ฑด ํ๋ผ๋ฏธํฐ๋ก ๋ฃ์ ๋ฌธ์์ด๋ ๋ค์งํ๊ณ ๋ฆฌํดํ ๋ฌธ์์ด ์ฃผ์๋ ๋ค์งํ ์๋ณธ ๋ฌธ์์ด์ ์ฃผ์๋ฅผ ์ค๋ค๋ ๊ฒ์ด๋ค!
- ์ ์ด์ parameter๋ฅผ const๋ก ๋ฐ์ง ์์์ผ๋ ์์ธก ๊ฐ๋ฅํ ๊ฒฐ๊ณผ์ธ๊ฑฐ ๊ฐ์๋ฐ, ๋ค๋ฅธ ์ธ์ด์์๋ ์๋ณธ ๋ฌธ์์ด์ ๊ฑด๋๋ฆฌ์ง ์๊ณ reverse ๋ฌธ์์ด์ ๊ตฌํ๋ค๋ ์ ์์ ์ ์ ํ ๊ฒ ๊ฐ๋ค.
- goto๋ฅผ ์ฐ๋ฉด ์๋๋ค๋ ์๋ฐ์ด ์ธ์ ๋ถํฐ ์์๋๋์ง ๋ชฐ๋ผ๋, C์ธ์ด์์ nested for loop์ break ํ๋ ์ผ์ด ๋ง๋ฅ ์ฝ์ง๋ง์ ์์๋ค. ๊ทธ๋ฅ ์ํธํ๊ฒ goto ์ฐ๋๊ฒ ๊น๋ํ ๊ฒ ๊ฐ๋ค.