Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n). If d(a) = b and d(b) = a, where a โ b, then a and b are an amicable pair and each of a and b are called amicable numbers.
For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220.
Evaluate the sum of all the amicable numbers under 10000.
Korean: http://euler.synap.co.kr/prob_detail.php?id=21
English: https://projecteuler.net/problem=21
- Tool: Visual Studio Code 1.42.1
- Extension: C# for Visual Studio Code
- SDK: .NET Core 3.1.100
- Download: https://dotnet.microsoft.com/download
- Language: C#
Change directory git root: /Problem21 and compile
dotnet runRun
/bin/Debug/netcoreapp3.1/Problem21.exe- Open folder "Problem21" by Visual Studio Code
- Check out settings: launch.json and tasks.json
- Press Ctrl + Shift + B to Build
- Press F5 to debug start
- ์ฝ์๋ฅผ ๊ตฌํ๋ ๊ฒ๋ ์์๋ฅผ ๊ตฌํ๋ ๊ฒ๋ถํฐ ์์ํด์ ์๊ฒ ๋ ์ง์์ด๊ธฐ๋ ํ๊ณ , ํ๋ก์ ํธ ์ค์ผ๋ฌ๋ฅผ ๊ดํตํ๋ ์ค์ํ ์ํ์ ์ง์์ด๊ธฐ๋ ํ๋ค.
- ๋ฌธ์ ์์ 220, 284์ ์ฝ์๋ฅผ ๊ฐ๊ฐ ๊ตฌํ๊ณ ๊ทธ ํฉ์ ๋น๊ต๋ฅผ ํ์ผ๋ฏ๋ก
- SumOfDivisor(n)์ ์ค๋นํ๋๋ฐ ์ด๊ฑด SumOfDivisor(220) == SumOfDivior(284)๊ฐ ๊ฐ๋ค๋ ๊ฑธ ํ์ธํ๊ธฐ ์ํด์ ์ค๋น ํ๋ค.
- ์ฝ์์ ํน์ฑ์ (๊ทธ๋ฆฌ๊ณ ์์์ ํน์ฑ์ ํฌํจํ์ฌ) ์ต์ 2๋ก ๋๋ ๋ชซ ์ด์์ for๋ฌธ์ ๋๋ฆด ํ์๊ฐ ์๋ค.
- ์ฆ, 220์ ๊ฒฝ์ฐ ์๊ธฐ ์์ ์ ์ ์ธํ ๊ฐ์ฅ ํฐ ์ฝ์๋ 110์ด๊ณ ์ด๋ ์์ 2๋ก ๋๋์ด์ง๋ ๋ชซ์ผ ๋ 111 ~ 220 ๊น์ง์ ์ ์ค์ ์ฝ์๊ฐ ์๋์ง๋ฅผ ์ฐพ์ผ๋ ค๊ณ for loop์ ๋๋ฆด ํ์๊ฐ ์๋ค๋ ๋ป์ด๊ธฐ๋ ํ๋ค.
- ์ด ํจ์๋ ์ด๋ฐ์์ผ๋ก ์ต์ ํ๋ฅผ ์งํํ๋ค.
- 10000 ๊น์ง for๋ฌธ์ ๋๋ฆฌ๊ณ ํด๋น ์ ์์ ๋ฐ๋ฅธ ์ฝ์์ ํฉ์ ๊ตฌํ๋ SumOfDivisor(i)๋ฅผ ํธ์ถํ์ฌ ๊ทธ ๊ฒฐ๊ณผ๋ฅผ sum1์ ๋ด๋๋ค.
- ๋ค์ SumOfDivisor(sum1)์ ํธ์ถํด ๋ณด๊ณ ๊ทธ ๊ฒฐ๊ณผ๋ฅผ sum2์ ๋ด๋๋ค.
- sum2 == i ์ธ์ง ํ๋จํ๋ค.
- sum2 == i ๋ผ๋ฉด i + sum2๋ฅผ ํ๊ณ AmicableSum ๋ณ์์ ๊ณ์ ๋์ ํ๋ค.
- ๋ฌธ์ ์ d(a) = b and d(b) = a, where a โ b ์กฐ๊ฑด์ด ์์ผ๋ฏ๋ก sum1 != sum2 ์กฐ๊ฑด์ ๊ฑธ์ด์ค๋ค.
- ์ฐธ๊ณ ๋ก ์ด ์ซ์๋ 10000๊น์ง for๋ฌธ ๋๋ฆฌ๋ฉด 4๊ฐ๊ฐ ๋์ค๋๋ฐ 6, 28, 496, 8628์ด ๋์จ๋ค.
- ์ด ์ซ์๋ ์ ์ธํ๋ ์กฐ๊ฑด์ ์ถ๊ฐํ๋ค.
- ์ต์ข if๋ฌธ์ ํํ๋ ์๋์ ๊ฐ๊ฒ ๋๋ค.
if (sum2 == i && sum1 != sum2)- ๋ง์ง๋ง์ผ๋ก AmicableSum ๊ฐ์ 2๋ก ๋๋์ด ์ถ๋ ฅํด์ผ ํ๋๋ฐ, ์ด์ ๋ 220์ผ ๋ 220+280์ ํ๊ณ 280์ผ ๋๋ 280+220์ด ๋๋ฉฐ ์ดํ amicalble number๊ฐ ๋ ์์ผ๋ก ์์ฑ๋๋ฏ๋ก ์ต์ข ์ ์ผ๋ก 2๋ก ๋๋ ๊ฐ์ ํฉ์ผ๋ก ์ป์ด๋ธ๋ค.