├── .gitattributes ├── .gitignore ├── LICENSE ├── Readme.md ├── script └── readme_generator.rb └── src ├── 001. Multiples of 3 and 5 ├── 001.c ├── 001.cpp ├── 001.go ├── 001.hs ├── 001.java ├── 001.lua ├── 001.py └── 001.rb ├── 002. Even Fibonacci numbers ├── 002.c ├── 002.cpp ├── 002.go ├── 002.java ├── 002.lua ├── 002.py └── 002.rb ├── 003. Largest prime factor ├── 003.c ├── 003.cpp ├── 003.go ├── 003.lua └── 003.rb ├── 004. Largest palindrome product ├── 004.cpp ├── 004.hs ├── 004.lua ├── 004.py └── 004.rb ├── 005. Smallest multiple ├── 005.lua ├── 005.py └── 005.rb ├── 006. Sum square difference ├── 006.c ├── 006.cpp ├── 006.go ├── 006.hs ├── 006.lua ├── 006.py └── 006.rb ├── 007. 10001st prime ├── 007.cpp ├── 007.go ├── 007.java ├── 007.lua └── 007.rb ├── 008. Largest product in a series ├── 008.py ├── 008.rb └── 008.txt ├── 009. Special Pythagorean triplet ├── 009.c ├── 009.cpp ├── 009.hs ├── 009.lua ├── 009.py └── 009.rb ├── 010. Summation of primes ├── 010.go ├── 010.java ├── 010.lua └── 010.rb ├── 011. Largest product in a grid ├── 011.lua └── 011.rb ├── 012. Highly divisible triangular number ├── 012.c ├── 012.cpp ├── 012.go ├── 012.java ├── 012.lua ├── 012.py └── 012.rb ├── 013. Large sum ├── 013.py ├── 013.rb └── 013.txt ├── 014. Longest Collatz sequence ├── 014.c ├── 014.cpp ├── 014.hs ├── 014.lua ├── 014.py └── 014.rb ├── 015. Lattice paths ├── 015.lua └── 015.rb ├── 016. Power digit sum ├── 016.go ├── 016.hs ├── 016.java ├── 016.py └── 016.rb ├── 017. Number letter counts ├── 017.c ├── 017.cpp ├── 017.go ├── 017.hs ├── 017.java ├── 017.lua ├── 017.py └── 017.rb ├── 018. Maximum path sum I ├── 018.py ├── 018.rb └── 018.txt ├── 019. Counting Sundays ├── 019.go ├── 019.java ├── 019.py └── 019.rb ├── 020. Factorial digit sum ├── 020.go ├── 020.hs ├── 020.java ├── 020.py └── 020.rb ├── 021. Amicable numbers └── 021.rb ├── 022. Names scores ├── 022.cpp ├── 022.lua ├── 022.rb └── p022_names.txt ├── 023. Non-abundant sums └── 023.rb ├── 024. Lexicographic permutations ├── 024.py └── 024.rb ├── 025. 1000-digit Fibonacci number ├── 025.go ├── 025.java ├── 025.py └── 025.rb ├── 026. Reciprocal cycles ├── 026.lua └── 026.rb ├── 027. Quadratic primes └── 027.rb ├── 028. Number spiral diagonals ├── 028.c ├── 028.cpp └── 028.lua ├── 029. Distinct powers ├── 029.go ├── 029.hs ├── 029.java ├── 029.py └── 029.rb ├── 030. Digit fifth powers ├── 030.c ├── 030.cpp ├── 030.go ├── 030.java ├── 030.py └── 030.rb ├── 031. Coin sums ├── 031.go ├── 031.lua ├── 031.py └── 031.rb ├── 032. Pandigital products └── 032.rb ├── 033. Digit cancelling fractions ├── 033.py └── 033.rb ├── 034. Digit factorials ├── 034.c ├── 034.cpp ├── 034.go ├── 034.lua ├── 034.py └── 034.rb ├── 035. Circular primes └── 035.rb ├── 036. Double-base palindromes ├── 036.go ├── 036.java ├── 036.lua └── 036.rb ├── 037. Truncatable primes └── 037.rb ├── 038. Pandigital multiples └── 038.rb ├── 039. Integer right triangles └── 039.go ├── 040. Champernowne's constant ├── 040.cpp ├── 040.go ├── 040.hs ├── 040.java ├── 040.lua ├── 040.py └── 040.rb ├── 041. Pandigital prime └── 041.rb ├── 042. Coded triangle numbers ├── 042.rb └── p042_words.txt ├── 043. Sub-string divisibility ├── 043.py └── 043.rb ├── 044. Pentagon numbers ├── 044.cpp └── 044.java ├── 045. Triangular, pentagonal, and hexagonal ├── 045.java ├── 045.lua └── 045.rb ├── 046. Goldbach's other conjecture └── 046.rb ├── 047. Distinct primes factors └── 047.rb ├── 048. Self powers ├── 048.go ├── 048.hs ├── 048.java ├── 048.py └── 048.rb ├── 049. Prime permutations └── 049.rb ├── 050. Consecutive prime sum └── 050.rb ├── 051. Prime digit replacements └── 051.rb ├── 052. Permuted multiples ├── 052.hs ├── 052.java ├── 052.lua ├── 052.py └── 052.rb ├── 053. Combinatoric selections ├── 053.go ├── 053.java ├── 053.py └── 053.rb ├── 054. Poker hands ├── 054.rb └── p054_poker.txt ├── 055. Lychrel numbers ├── 055.py └── 055.rb ├── 056. Powerful digit sum ├── 056.hs ├── 056.java ├── 056.py └── 056.rb ├── 057. Square root convergents ├── 057.py └── 057.rb ├── 058. Spiral primes └── 058.rb ├── 059. XOR decryption ├── 059.lua ├── 059.rb ├── common_english_words.txt └── p059_cipher.txt ├── 062. Cubic permutations ├── 062.java └── 062.rb ├── 063. Powerful digit counts ├── 063.c ├── 063.cpp ├── 063.go ├── 063.lua ├── 063.py └── 063.rb ├── 064. Odd period square roots ├── 064.py └── 064.rb ├── 065. Convergents of e ├── 065.py └── 065.rb ├── 067. Maximum path sum II ├── 067.py ├── 067.rb └── p067_triangle.txt ├── 069. Totient maximum └── 069.rb ├── 071. Ordered fractions ├── 071.go ├── 071.py └── 071.rb ├── 072. Counting fractions └── 072.rb ├── 073. Counting fractions in a range ├── 073.py └── 073.rb ├── 074. Digit factorial chains ├── 074.cpp ├── 074.py └── 074.rb ├── 076. Counting summations ├── 076.go ├── 076.lua ├── 076.py └── 076.rb ├── 077. Prime summations └── 077.rb ├── 080. Square root digital expansion └── 080.rb ├── 081. Path sum two ways ├── 081.rb └── p081_matrix.txt ├── 085. Counting rectangles ├── 085.go └── 085.rb ├── 087. Prime power triples └── 087.rb ├── 089. Roman numerals ├── 089.lua ├── 089.rb └── p089_roman.txt ├── 092. Square digit chains ├── 092.cpp ├── 092.go ├── 092.java └── 092.lua ├── 097. Large non-Mersenne prime ├── 097.go ├── 097.hs ├── 097.java ├── 097.py └── 097.rb ├── 099. Largest exponential ├── 099.c ├── 099.cpp ├── 099.lua ├── 099.py ├── 099.rb └── p099_base_exp.txt ├── 102. Triangle containment ├── 102.cpp ├── 102.go └── p102_triangles.txt ├── 104. Pandigital Fibonacci ends ├── 104.py └── 104.rb ├── 112. Bouncy numbers ├── 112.cpp ├── 112.go ├── 112.java └── 112.rb ├── 113. Non-bouncy numbers ├── 113.lua ├── 113.py └── 113.rb ├── 116. Red, green or blue tiles ├── 116.java ├── 116.py └── 116.rb ├── 119. Digit power sum ├── 119.py └── 119.rb ├── 120. Square remainders ├── 120.go ├── 120.java ├── 120.py └── 120.rb ├── 123. Prime square remainders └── 123.rb ├── 125. Palindromic sums ├── 125.py └── 125.rb ├── 145. How many reversible numbers are there below one-billion ├── 145.c ├── 145.cpp ├── 145.go ├── 145.java ├── 145.lua ├── 145.py └── 145.rb ├── 146. Investigating a Prime Pattern ├── 146.java └── 146.rb ├── 179. Consecutive positive divisors ├── 179.cpp └── 179.java ├── 187. Semiprimes ├── 187.cpp └── 187.rb ├── 188. The hyperexponentiation of a number ├── 188.go ├── 188.java └── 188.rb ├── 204. Generalised Hamming Numbers ├── 204.cpp └── 204.java ├── 205. Dice Game ├── 205.go ├── 205.py └── 205.rb ├── 206. Concealed Square ├── 206.go ├── 206.java ├── 206.lua ├── 206.py └── 206.rb ├── 301. Nim ├── 301.c ├── 301.cpp ├── 301.go ├── 301.java └── 301.lua ├── 346. Strong Repunits ├── 346.py └── 346.rb ├── 348. Sum of a square and a cube ├── 348.cpp ├── 348.java ├── 348.py └── 348.rb ├── 357. Prime generating integers ├── 357.cpp ├── 357.go └── 357.rb ├── 387. Harshad Numbers └── 387.rb ├── 504. Square on the Inside └── 504.rb ├── 587. Concave triangle ├── 587.c ├── 587.cpp ├── 587.go └── 587.java └── 622. Riffle Shuffles └── 622.rb /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | 4 | # Custom for Visual Studio 5 | *.cs diff=csharp 6 | *.sln merge=union 7 | *.csproj merge=union 8 | *.vbproj merge=union 9 | *.fsproj merge=union 10 | *.dbproj merge=union 11 | 12 | # Standard to msysgit 13 | *.doc diff=astextplain 14 | *.DOC diff=astextplain 15 | *.docx diff=astextplain 16 | *.DOCX diff=astextplain 17 | *.dot diff=astextplain 18 | *.DOT diff=astextplain 19 | *.pdf diff=astextplain 20 | *.PDF diff=astextplain 21 | *.rtf diff=astextplain 22 | *.RTF diff=astextplain 23 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 Yu Hao 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /src/001. Multiples of 3 and 5/001.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main(void) { 4 | int sum = 0; 5 | for (int i = 0; i < 1000; i++) { 6 | if (i % 3 == 0 || i % 5 == 0) { 7 | sum += i; 8 | } 9 | } 10 | printf("%d\n", sum); 11 | return 0; 12 | } 13 | -------------------------------------------------------------------------------- /src/001. Multiples of 3 and 5/001.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main(void) { 4 | int sum = 0; 5 | for (int i = 0; i < 1000; i++) { 6 | if (i % 3 == 0 || i % 5 == 0) { 7 | sum += i; 8 | } 9 | } 10 | std::cout << sum; 11 | } 12 | -------------------------------------------------------------------------------- /src/001. Multiples of 3 and 5/001.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | sum := 0 7 | for i := 0; i < 1000; i++ { 8 | if i % 3 == 0 || i % 5 == 0 { 9 | sum += i 10 | } 11 | } 12 | fmt.Println(sum) 13 | } -------------------------------------------------------------------------------- /src/001. Multiples of 3 and 5/001.hs: -------------------------------------------------------------------------------- 1 | main = print $ sum [a | a <- [1..999], a `mod` 3 == 0 || a `mod` 5 == 0] 2 | -------------------------------------------------------------------------------- /src/001. Multiples of 3 and 5/001.java: -------------------------------------------------------------------------------- 1 | import java.util.stream.IntStream; 2 | 3 | public class Main { 4 | 5 | public static void main(String[] args) { 6 | int sum = IntStream.range(1, 1000) 7 | .filter(n -> n % 3 == 0 || n % 5 == 0) 8 | .sum(); 9 | System.out.println(sum); 10 | } 11 | 12 | } -------------------------------------------------------------------------------- /src/001. Multiples of 3 and 5/001.lua: -------------------------------------------------------------------------------- 1 | sum = 0 2 | for i = 1, 999 do 3 | if i % 3 == 0 or i % 5 == 0 then 4 | sum = sum + i 5 | end 6 | end 7 | 8 | print(sum) -------------------------------------------------------------------------------- /src/001. Multiples of 3 and 5/001.py: -------------------------------------------------------------------------------- 1 | sum = 0 2 | for i in range(1000): 3 | if i % 3 == 0 or i % 5 == 0: 4 | sum += i 5 | 6 | print(sum) 7 | -------------------------------------------------------------------------------- /src/001. Multiples of 3 and 5/001.rb: -------------------------------------------------------------------------------- 1 | puts (1 ... 1000).to_a.find_all {|i| i % 3 == 0 or i % 5 == 0} .inject(:+) -------------------------------------------------------------------------------- /src/002. Even Fibonacci numbers/002.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main(void) { 4 | long long f1 = 1, f2 = 1; 5 | long long sum = 0; 6 | while (f1 < 4000000LL) { 7 | long long temp = f2; 8 | f2 = f1 + f2; 9 | f1 = temp; 10 | if (f1 % 2 == 0) { 11 | sum += f1; 12 | } 13 | } 14 | printf("%lld\n", sum); 15 | return 0; 16 | } 17 | -------------------------------------------------------------------------------- /src/002. Even Fibonacci numbers/002.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main(void) { 5 | std::map fibonacci; 6 | fibonacci[1] = 1; 7 | fibonacci[2] = 2; 8 | int i = 2; 9 | 10 | while (fibonacci[i] < 4000000) { 11 | ++i; 12 | fibonacci[i] = fibonacci[i - 1] + fibonacci[i - 2]; 13 | } 14 | 15 | long long sum = 0; 16 | for (const auto& i : fibonacci) { 17 | if (i.second % 2 == 0) { 18 | sum += i.second; 19 | } 20 | } 21 | std::cout << sum << std::endl; 22 | } 23 | -------------------------------------------------------------------------------- /src/002. Even Fibonacci numbers/002.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main () { 6 | f := make(map[int]int) 7 | f[1] = 1 8 | f[2] = 1 9 | 10 | for i := 3; ; i++ { 11 | f[i] = f[i - 2] + f[i - 1] 12 | if f[i] > 4000000 { 13 | break 14 | } 15 | } 16 | 17 | sum := 0 18 | for _, v := range f { 19 | if v % 2 == 0 { 20 | sum += v 21 | } 22 | } 23 | 24 | fmt.Println(sum) 25 | } 26 | -------------------------------------------------------------------------------- /src/002. Even Fibonacci numbers/002.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | public static void main(String args[]) { 3 | long f1 = 1; 4 | long f2 = 2; 5 | 6 | long sum = 0; 7 | while (f1 < 4_000_000) { 8 | if (f1 % 2 == 0) { 9 | sum += f1; 10 | } 11 | long temp = f2; 12 | f2 = f1 + f2; 13 | f1 = temp; 14 | } 15 | System.out.println(sum); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/002. Even Fibonacci numbers/002.lua: -------------------------------------------------------------------------------- 1 | local a1, a2 = 1, 2 2 | local sum = 0 3 | 4 | while a1 < 4000000 do 5 | a1, a2 = a2, a1 + a2 6 | if a1 % 2 == 0 then 7 | sum = sum + a1 8 | end 9 | end 10 | 11 | print(sum) -------------------------------------------------------------------------------- /src/002. Even Fibonacci numbers/002.py: -------------------------------------------------------------------------------- 1 | values = [] 2 | n1 = 1 3 | n2 = 2 4 | while n1 < 4000000: 5 | n1, n2 = n2, n1 + n2 6 | values.append(n1) 7 | 8 | print(sum([x for x in values if x % 2 == 0])) 9 | -------------------------------------------------------------------------------- /src/002. Even Fibonacci numbers/002.rb: -------------------------------------------------------------------------------- 1 | values = [] 2 | n1 = 1 3 | n2 = 2 4 | while n1 < 4000000 5 | n1, n2 = n2, n1 + n2 6 | values << n1 7 | end 8 | 9 | puts values.find_all {|i| i % 2 == 0}.inject(:+) -------------------------------------------------------------------------------- /src/003. Largest prime factor/003.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | long long max_prime_factor(long long num); 4 | 5 | int main(void) { 6 | printf("%lld\n", max_prime_factor(600851475143LL)); 7 | return 0; 8 | } 9 | 10 | long long max_prime_factor(long long num) { 11 | // 2 is the only even prime number 12 | while (num % 2 == 0) { 13 | num /= 2; 14 | } 15 | 16 | long long max = 2; 17 | long long factor = 3; 18 | while (num > 1) { 19 | while (num % factor == 0) { 20 | num /= factor; 21 | max = factor; 22 | } 23 | factor += 2; 24 | } 25 | return max; 26 | } 27 | -------------------------------------------------------------------------------- /src/003. Largest prime factor/003.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | long long max_prime_factor(long long num); 4 | 5 | int main(void) { 6 | std::cout << max_prime_factor(600851475143LL) << std::endl; 7 | return 0; 8 | } 9 | 10 | long long max_prime_factor(long long num) { 11 | // 2 is the only even prime number 12 | while (num % 2 == 0) { 13 | num /= 2; 14 | } 15 | 16 | long long max = 2; 17 | long long factor = 3; 18 | while (num > 1) { 19 | while (num % factor == 0) { 20 | num /= factor; 21 | max = factor; 22 | } 23 | factor += 2; 24 | } 25 | return max; 26 | } 27 | -------------------------------------------------------------------------------- /src/003. Largest prime factor/003.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | fmt.Println(maxPrimeFactor(600851475143)) 7 | } 8 | 9 | func maxPrimeFactor(num int) int { 10 | // 2 is the only even prime 11 | for num % 2 == 0 { 12 | num /= 2 13 | } 14 | 15 | max := 2 16 | for factor := 3; num > 1; factor += 2 { 17 | for num % factor == 0 { 18 | num /= factor 19 | max = factor 20 | } 21 | } 22 | return max 23 | } -------------------------------------------------------------------------------- /src/003. Largest prime factor/003.lua: -------------------------------------------------------------------------------- 1 | local num = 600851475143 2 | local max = 0 3 | while num % 2 == 0 do 4 | num = num / 2 5 | max = 2 6 | end 7 | 8 | for f = 3, num, 2 do 9 | while num % f == 0 do 10 | num = num / f 11 | max = f 12 | end 13 | if num == 1 then 14 | break 15 | end 16 | end 17 | 18 | print(max) -------------------------------------------------------------------------------- /src/003. Largest prime factor/003.rb: -------------------------------------------------------------------------------- 1 | require 'prime' 2 | 3 | puts 600851475143.prime_division[-1][0] 4 | -------------------------------------------------------------------------------- /src/004. Largest palindrome product/004.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using std::string; 4 | 5 | bool is_palindrome(long long num); 6 | 7 | int main() { 8 | long long max = 0; 9 | for (int i = 999; i >= 100; --i) { 10 | for (int j = 999; j >= 100; --j) { 11 | long long product = i * j; 12 | if (is_palindrome(product)) { 13 | if (product > max) { 14 | max = product; 15 | } 16 | } 17 | } 18 | } 19 | std::cout << max << std::endl; 20 | } 21 | 22 | bool is_palindrome(long long num) { 23 | string original = std::to_string(num); 24 | string reversed(original.rbegin(), original.rend()); 25 | return original == reversed; 26 | } 27 | -------------------------------------------------------------------------------- /src/004. Largest palindrome product/004.hs: -------------------------------------------------------------------------------- 1 | main = print $ maximum palindromes 2 | 3 | isPalindrome :: Int -> Bool 4 | isPalindrome n = (show n) == (reverse $ show n) 5 | 6 | palindromes = [a * b | a <- [100 .. 999], b <- [100 .. 999], isPalindrome $ a * b] 7 | -------------------------------------------------------------------------------- /src/004. Largest palindrome product/004.lua: -------------------------------------------------------------------------------- 1 | local max = 0 2 | for a = 999, 100, -1 do 3 | for b = 999, 100, -1 do 4 | local num = a * b 5 | if num == tonumber(tostring(num):reverse()) then 6 | if num > max then 7 | max = num 8 | end 9 | end 10 | end 11 | end 12 | print(max) -------------------------------------------------------------------------------- /src/004. Largest palindrome product/004.py: -------------------------------------------------------------------------------- 1 | def is_palindrome(n): 2 | return str(n)[::-1] == str(n) 3 | 4 | max_n = 0 5 | for a in range(999, 100, -1): 6 | for b in range(999, 100, -1): 7 | n = a * b 8 | if n > max_n and is_palindrome(n): 9 | max_n = n 10 | print(max_n) 11 | -------------------------------------------------------------------------------- /src/004. Largest palindrome product/004.rb: -------------------------------------------------------------------------------- 1 | class Integer 2 | def is_palindrome? 3 | return self == self.to_s.reverse.to_i 4 | end 5 | end 6 | 7 | max_n = 0 8 | 999.downto(100) do |a| 9 | 999.downto(100) do |b| 10 | n = a * b 11 | if n > max_n and n.is_palindrome? 12 | max_n = n 13 | end 14 | end 15 | end 16 | 17 | puts max_n 18 | -------------------------------------------------------------------------------- /src/005. Smallest multiple/005.lua: -------------------------------------------------------------------------------- 1 | print(2^4 * 3^2 * 5 * 7 * 11 * 13 * 17 * 19) -------------------------------------------------------------------------------- /src/005. Smallest multiple/005.py: -------------------------------------------------------------------------------- 1 | print(2 ** 4 * 3 ** 2 * 5 * 7 * 11 * 13 * 17 * 19) 2 | -------------------------------------------------------------------------------- /src/005. Smallest multiple/005.rb: -------------------------------------------------------------------------------- 1 | puts 2 ** 4 * 3 ** 2 * 5 * 7 * 11 * 13 * 17 * 19 -------------------------------------------------------------------------------- /src/006. Sum square difference/006.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main(void) { 4 | int sum100pow = 0; 5 | for (int i = 1; i <= 100; ++i) { 6 | sum100pow += i * i; 7 | } 8 | int sum100 = 100 * (100 + 1) / 2; 9 | printf("%d\n", sum100 * sum100 - sum100pow); 10 | } 11 | -------------------------------------------------------------------------------- /src/006. Sum square difference/006.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main(void) { 4 | int sum100pow = 0; 5 | for (int i = 1; i <= 100; ++i) { 6 | sum100pow += i * i; 7 | } 8 | int sum100 = 100 * (100 + 1) / 2; 9 | std::cout << sum100 * sum100 - sum100pow << std::endl; 10 | } 11 | -------------------------------------------------------------------------------- /src/006. Sum square difference/006.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | var sum100pow int 7 | for i := 1; i <= 100; i++ { 8 | sum100pow += i * i 9 | } 10 | sum100 := 100 * (100 + 1) / 2 11 | fmt.Println(sum100 * sum100 - sum100pow) 12 | } 13 | -------------------------------------------------------------------------------- /src/006. Sum square difference/006.hs: -------------------------------------------------------------------------------- 1 | main = print $ (sum [1..100])^2 - (sum $ map (^2) [1..100]) 2 | -------------------------------------------------------------------------------- /src/006. Sum square difference/006.lua: -------------------------------------------------------------------------------- 1 | sum100pow = 0 2 | for i = 1, 100 do 3 | sum100pow = sum100pow + i * i 4 | end 5 | sum100 = 100 * (100 + 1) / 2 6 | print(sum100 * sum100 - sum100pow) 7 | -------------------------------------------------------------------------------- /src/006. Sum square difference/006.py: -------------------------------------------------------------------------------- 1 | sum_of_square = sum([x * x for x in range(1, 101)]) 2 | sqare_of_sum = sum(range(1, 101)) 3 | 4 | print(sqare_of_sum ** 2 - sum_of_square) 5 | -------------------------------------------------------------------------------- /src/006. Sum square difference/006.rb: -------------------------------------------------------------------------------- 1 | sum_of_square = (1 .. 100).inject { |sum, n| sum + n * n} 2 | sqare_of_sum = (1 .. 100).inject(:+) ** 2 3 | 4 | puts sqare_of_sum - sum_of_square -------------------------------------------------------------------------------- /src/007. 10001st prime/007.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using std::vector; 6 | 7 | vector gen_primes(long long n); 8 | 9 | int main() { 10 | vector primes = gen_primes(200000); 11 | // index starts from 0 12 | std::cout << primes[10000] << std::endl; 13 | return 0; 14 | } 15 | 16 | vector gen_primes(long long n) { 17 | // Sieve of Eratosthenes 18 | vector sieve(n + 1); 19 | sieve[0] = false; // so that the index starts from 1 20 | for (long long i = 1; i <= n; ++i) { 21 | if (i % 2 == 0) { 22 | sieve[i] = false; 23 | } else { 24 | sieve[i] = true; 25 | } 26 | } 27 | 28 | sieve[1] = false; // 1 is not prime 29 | sieve[2] = true; // 2 is the only even prime 30 | 31 | long long factor = 3; 32 | while (factor <= int(std::sqrt(n))) { 33 | for (long long i = factor * factor; i < n; i += factor) { 34 | sieve[i] = false; 35 | } 36 | do { 37 | factor += 2; 38 | } while (sieve[factor] == false); 39 | } 40 | 41 | vector primes; 42 | for (long long i = 0; i <= sieve.size(); ++i) { 43 | if (sieve[i]) { 44 | primes.push_back(i); 45 | } 46 | } 47 | return primes; 48 | } 49 | -------------------------------------------------------------------------------- /src/007. 10001st prime/007.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "math" 6 | ) 7 | 8 | func main() { 9 | primes := genPrimes(200000) 10 | count := 0 11 | for i := 1; i < len(primes); i++ { 12 | if primes[i] { 13 | count++ 14 | } 15 | if count == 10001 { 16 | fmt.Println(i) 17 | break 18 | } 19 | } 20 | } 21 | 22 | func genPrimes(n int) []bool { 23 | // Sieve of Eratosthenes 24 | sieve := make([]bool, n + 1) 25 | sieve[0] = false // so that the index starts from 1 26 | for i := 1; i < n; i++ { 27 | if i % 2 == 0 { 28 | sieve[i] = false 29 | } else { 30 | sieve[i] = true 31 | } 32 | } 33 | sieve[1] = false // 1 is not prime 34 | sieve[2] = true // 2 is the only even prime 35 | 36 | factor := 3 37 | for factor <= int(math.Sqrt(float64(n))) { 38 | for i := factor * factor; i < n; i += factor { 39 | sieve[i] = false 40 | } 41 | factor += 2 42 | for sieve[factor] == false { 43 | factor += 2 44 | } 45 | } 46 | return sieve 47 | } 48 | -------------------------------------------------------------------------------- /src/007. 10001st prime/007.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | public class Main { 4 | 5 | public static void main(String[] args) { 6 | ArrayList primes = genPrimes(200_000); 7 | // index starts from 0 8 | System.out.println(primes.get(10_000)); 9 | 10 | } 11 | 12 | private static ArrayList genPrimes(int n) { 13 | // Sieve of Eratosthenes 14 | boolean[] sieve = new boolean[n + 1]; 15 | sieve[0] = false; // so that the index starts from 1 16 | for (int i = 1; i <= n; ++i) { 17 | if (i % 2 == 0) { 18 | sieve[i] = false; 19 | } else { 20 | sieve[i] = true; 21 | } 22 | } 23 | 24 | sieve[1] = false; // 1 is not prime 25 | sieve[2] = true; // 2 is the only even prime 26 | 27 | int factor = 3; 28 | while (factor <= (int)Math.sqrt(n)) { 29 | for (int i = factor * factor; i < n; i += factor) { 30 | sieve[i] = false; 31 | } 32 | do { 33 | factor += 2; 34 | } while (!sieve[factor]); 35 | } 36 | 37 | ArrayList primes = new ArrayList<>(); 38 | for (int i = 0; i < sieve.length; ++i) { 39 | if (sieve[i]) { 40 | primes.add(i); 41 | } 42 | } 43 | return primes; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/007. 10001st prime/007.lua: -------------------------------------------------------------------------------- 1 | function gen_primes(n) 2 | --Sieve of Eratosthenes 3 | local sieve = {} 4 | for i = 1, n do 5 | if i % 2 == 0 then 6 | sieve[i] = false 7 | else 8 | sieve[i] = true 9 | end 10 | end 11 | sieve[1] = false -- 1 is not prime 12 | sieve[2] = true -- 2 is the only even prime 13 | 14 | local factor = 3 15 | while factor <= math.sqrt(#sieve) do 16 | for i = factor * factor, #sieve, factor do 17 | sieve[i] = false 18 | end 19 | repeat 20 | factor = factor + 2 21 | until sieve[factor] == true 22 | end 23 | return sieve 24 | end 25 | 26 | n = 200000 27 | primes = gen_primes(n) 28 | local count = 0 29 | for i = 1, n do 30 | if primes[i] then 31 | count = count + 1 32 | end 33 | if count == 10001 then 34 | print(i) 35 | break 36 | end 37 | end -------------------------------------------------------------------------------- /src/007. 10001st prime/007.rb: -------------------------------------------------------------------------------- 1 | require 'prime' 2 | 3 | puts Prime.each.take(10001).last -------------------------------------------------------------------------------- /src/008. Largest product in a series/008.py: -------------------------------------------------------------------------------- 1 | from functools import reduce 2 | from operator import mul 3 | 4 | with open("008.txt") as f: 5 | digits = [int(d) for d in f.read()] 6 | max_product = 0 7 | for i in range(0, len(digits) - 12): 8 | product = reduce(mul, digits[i:i + 13]) 9 | if product > max_product: 10 | max_product = product 11 | print(max_product) 12 | -------------------------------------------------------------------------------- /src/008. Largest product in a series/008.rb: -------------------------------------------------------------------------------- 1 | num_str = File.read('008.txt') 2 | digits = num_str.chars.map(&:to_i) 3 | max_product = 0 4 | 0.upto(digits.length - 12) do |i| 5 | product = digits[i, 13].inject(:*) 6 | max_product = product if max_product < product 7 | end 8 | 9 | puts max_product 10 | -------------------------------------------------------------------------------- /src/008. Largest product in a series/008.txt: -------------------------------------------------------------------------------- 1 | 7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450 -------------------------------------------------------------------------------- /src/009. Special Pythagorean triplet/009.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main(void) { 4 | for (int a = 1; a < 1000; ++a) { 5 | for (int b = a; b < 1000; ++b) { 6 | int c = 1000 - a - b; 7 | if (c > b && a * a + b * b == c * c) { 8 | printf("%d\n", a * b * c); 9 | } 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/009. Special Pythagorean triplet/009.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() { 4 | for (int a = 1; a < 1000; ++a) { 5 | for (int b = a; b < 1000; ++b) { 6 | int c = 1000 - a - b; 7 | if (c > b && a * a + b * b == c * c) { 8 | std::cout << a * b * c << std::endl; 9 | } 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/009. Special Pythagorean triplet/009.hs: -------------------------------------------------------------------------------- 1 | main = print $ head [a * b * c | a <- [1 .. 1000], b <- [a .. 1000], let c = 1000 - a - b, b < c, a^2 + b^2 == c^2] 2 | -------------------------------------------------------------------------------- /src/009. Special Pythagorean triplet/009.lua: -------------------------------------------------------------------------------- 1 | for a = 1, 999 do 2 | for b = a, 999 do 3 | c = 1000 - a - b 4 | if (c * c == a *a + b * b) then 5 | print(a * b * c) 6 | return 7 | end 8 | end 9 | end -------------------------------------------------------------------------------- /src/009. Special Pythagorean triplet/009.py: -------------------------------------------------------------------------------- 1 | for a in range(1, 1000): 2 | for b in range(a, 1000): 3 | c = 1000 - a - b 4 | if a ** 2 + b ** 2 == c ** 2: 5 | print(a * b * c) 6 | exit() 7 | -------------------------------------------------------------------------------- /src/009. Special Pythagorean triplet/009.rb: -------------------------------------------------------------------------------- 1 | 1.upto(1000) do |a| 2 | a.upto(1000) do |b| 3 | c = 1000 - a - b 4 | if a ** 2 + b ** 2 == c ** 2 5 | puts a * b * c 6 | end 7 | end 8 | end -------------------------------------------------------------------------------- /src/010. Summation of primes/010.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "math" 6 | ) 7 | 8 | func main() { 9 | n := 2000000 10 | primes := genPrimes(n) 11 | sum := 0 12 | for i := 1; i < n; i++ { 13 | if (primes[i]) { 14 | sum += i 15 | } 16 | } 17 | fmt.Println(sum) 18 | } 19 | 20 | func genPrimes(n int) []bool { 21 | // Sieve of Eratosthenes 22 | sieve := make([]bool, n + 1) 23 | sieve[0] = false // so that the index starts from 1 24 | for i := 1; i < n; i++ { 25 | if i % 2 == 0 { 26 | sieve[i] = false 27 | } else { 28 | sieve[i] = true 29 | } 30 | } 31 | sieve[1] = false // 1 is not prime 32 | sieve[2] = true // 2 is the only even prime 33 | 34 | factor := 3 35 | for factor <= int(math.Sqrt(float64(n))) { 36 | for i := factor * factor; i < n; i += factor { 37 | sieve[i] = false 38 | } 39 | factor += 2 40 | for sieve[factor] == false { 41 | factor += 2 42 | } 43 | } 44 | return sieve 45 | } 46 | -------------------------------------------------------------------------------- /src/010. Summation of primes/010.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.List; 3 | 4 | public class Main { 5 | 6 | public static void main(String[] args) { 7 | final long upperLimit = 2_000_000; 8 | List primes = genPrimes(upperLimit); 9 | long sum = primes.stream().mapToLong(Long::longValue).sum(); 10 | System.out.println(sum); 11 | } 12 | 13 | private static List genPrimes(long n) { 14 | // Sieve of Eratosthenes 15 | boolean[] sieve = new boolean[(int)n + 1]; 16 | sieve[0] = false; // so that the index starts from 1 17 | for (int i = 1; i <= n; ++i) { 18 | if (i % 2 == 0) { 19 | sieve[i] = false; 20 | } else { 21 | sieve[i] = true; 22 | } 23 | } 24 | 25 | sieve[1] = false; // 1 is not prime 26 | sieve[2] = true; // 2 is the only even prime 27 | 28 | int factor = 3; 29 | while (factor <= (int)Math.sqrt(n)) { 30 | for (int i = factor * factor; i < n; i += factor) { 31 | sieve[i] = false; 32 | } 33 | do { 34 | factor += 2; 35 | } while (!sieve[factor]); 36 | } 37 | 38 | List primes = new ArrayList<>(); 39 | for (long i = 0; i < sieve.length; ++i) { 40 | if (sieve[(int)i]) { 41 | primes.add(i); 42 | } 43 | } 44 | return primes; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/010. Summation of primes/010.lua: -------------------------------------------------------------------------------- 1 | function gen_primes(n) 2 | --Sieve of Eratosthenes 3 | local sieve = {} 4 | for i = 1, n do 5 | if i % 2 == 0 then 6 | sieve[i] = false 7 | else 8 | sieve[i] = true 9 | end 10 | end 11 | sieve[1] = false -- 1 is not prime 12 | sieve[2] = true -- 2 is the only even prime 13 | 14 | local factor = 3 15 | while factor <= math.sqrt(#sieve) do 16 | for i = factor * factor, #sieve, factor do 17 | sieve[i] = false 18 | end 19 | repeat 20 | factor = factor + 2 21 | until sieve[factor] == true 22 | end 23 | return sieve 24 | end 25 | 26 | local n = 2000000 27 | primes = gen_primes(n) 28 | local sum = 0 29 | for i = 1, n do 30 | if primes[i] then 31 | sum = sum + i 32 | end 33 | end 34 | 35 | print(sum) 36 | 37 | -------------------------------------------------------------------------------- /src/010. Summation of primes/010.rb: -------------------------------------------------------------------------------- 1 | require 'prime' 2 | 3 | puts Prime.each(2000000).inject(:+) 4 | -------------------------------------------------------------------------------- /src/011. Largest product in a grid/011.lua: -------------------------------------------------------------------------------- 1 | local t = {08,02,22,97,38,15,00,40,00,75,04,05,07,78,52,12,50,77,91,08,49,49,99,40,17,81,18,57,60,87,17,40,98,43,69,48,04,56,62,00,81,49,31,73,55,79,14,29,93,71,40,67,53,88,30,03,49,13,36,65,52,70,95,23,04,60,11,42,69,24,68,56,01,32,56,71,37,02,36,91,22,31,16,71,51,67,63,89,41,92,36,54,22,40,40,28,66,33,13,80,24,47,32,60,99,03,45,02,44,75,33,53,78,36,84,20,35,17,12,50,32,98,81,28,64,23,67,10,26,38,40,67,59,54,70,66,18,38,64,70,67,26,20,68,02,62,12,20,95,63,94,39,63,08,40,91,66,49,94,21,24,55,58,05,66,73,99,26,97,17,78,78,96,83,14,88,34,89,63,72,21,36,23,09,75,00,76,44,20,45,35,14,00,61,33,97,34,31,33,95,78,17,53,28,22,75,31,67,15,94,03,80,04,62,16,14,09,53,56,92,16,39,05,42,96,35,31,47,55,58,88,24,00,17,54,24,36,29,85,57,86,56,00,48,35,71,89,07,05,44,44,37,44,60,21,58,51,54,17,58,19,80,81,68,05,94,47,69,28,73,92,13,86,52,17,77,04,89,55,40,04,52,08,83,97,35,99,16,07,97,57,32,16,26,26,79,33,27,98,66,88,36,68,87,57,62,20,72,03,46,33,67,46,55,12,32,63,93,53,69,04,42,16,73,38,25,39,11,24,94,72,18,08,46,29,32,40,62,76,36,20,69,36,41,72,30,23,88,34,62,99,69,82,67,59,85,74,04,36,16,20,73,35,29,78,31,90,01,74,31,49,71,48,86,81,16,23,57,05,54,01,70,54,71,83,51,54,69,16,92,33,48,61,43,52,01,89,19,67,48} 2 | 3 | local max = 0 4 | 5 | for m = 1, 20 do 6 | for n = 1, 17 do 7 | local prod = t[(m - 1) * 20 + n] * t[(m - 1) * 20 + n + 1] * t[(m - 1) * 20 + n + 2] * t[(m - 1) * 20 + n + 3] 8 | if (prod > max) then 9 | max = prod 10 | end 11 | end 12 | end 13 | 14 | for m = 1, 17 do 15 | for n = 1, 20 do 16 | local prod = t[(m - 1) * 20 + n] * t[m * 20 + n] * t[(m + 1) * 20 + n] * t[(m + 2) * 20 + n] 17 | if (prod > max) then 18 | max = prod 19 | end 20 | end 21 | end 22 | 23 | for m = 1, 17 do 24 | for n = 1, 17 do 25 | local prod = t[(m - 1) * 20 + n] * t[m * 20 + n + 1] * t[(m + 1) * 20 + n + 2] * t[(m + 2) * 20 + n + 3] 26 | if (prod > max) then 27 | max = prod 28 | end 29 | end 30 | end 31 | 32 | for m = 1, 17 do 33 | for n = 4, 20 do 34 | local prod = t[(m - 1) * 20 + n] * t[m * 20 + n - 1] * t[(m + 1) * 20 + n - 2] * t[(m + 2) * 20 + n - 3] 35 | if (prod > max) then 36 | max = prod 37 | end 38 | end 39 | end 40 | 41 | print(max) -------------------------------------------------------------------------------- /src/011. Largest product in a grid/011.rb: -------------------------------------------------------------------------------- 1 | str = 2 | '08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 3 | 49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 4 | 81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 5 | 52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91 6 | 22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80 7 | 24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50 8 | 32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70 9 | 67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21 10 | 24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72 11 | 21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95 12 | 78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92 13 | 16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57 14 | 86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58 15 | 19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40 16 | 04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66 17 | 88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69 18 | 04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36 19 | 20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16 20 | 20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54 21 | 01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48' 22 | mat = str.split("\n").map{|row| row.split} 23 | values = [] 24 | 0.upto(mat.size - 4) do |row| 25 | 0.upto(mat[row].size - 4) do |column| 26 | values << mat[row][column].to_i * mat[row + 1][column + 1].to_i * mat[row + 2][column + 2].to_i * mat[row + 3][column + 3].to_i 27 | end 28 | end 29 | 30 | 0.upto(mat.size - 4) do |row| 31 | 3.upto(mat[row].size - 1) do |column| 32 | values << mat[row][column].to_i * mat[row + 1][column - 1].to_i * mat[row + 2][column - 2].to_i * mat[row + 3][column - 3].to_i 33 | end 34 | end 35 | 36 | puts values.max -------------------------------------------------------------------------------- /src/012. Highly divisible triangular number/012.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int numOfFactors(long long num); 4 | 5 | int main() { 6 | long long triangle = 0; 7 | int i = 1; 8 | while (1) { 9 | triangle += i; 10 | if (numOfFactors(triangle) > 500) { 11 | printf("%lld\n", triangle); 12 | break; 13 | } 14 | ++i; 15 | } 16 | } 17 | 18 | int numOfFactors(long long num) { 19 | int count = 0; 20 | long factor = 1; 21 | while (factor * factor < num) { 22 | if (num % factor == 0) { 23 | count += 1; 24 | } 25 | factor += 1; 26 | } 27 | if (factor * factor > num) { 28 | return count * 2; 29 | } else { 30 | return count * 2 + 1; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/012. Highly divisible triangular number/012.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int numOfFactors(long long num); 4 | 5 | int main() { 6 | long long triangle = 0; 7 | int i = 1; 8 | while (true) { 9 | triangle += i; 10 | if (numOfFactors(triangle) > 500) { 11 | std::cout << triangle << std::endl; 12 | break; 13 | } 14 | ++i; 15 | } 16 | } 17 | 18 | int numOfFactors(long long num) { 19 | int count = 0; 20 | long factor = 1; 21 | while (factor * factor < num) { 22 | if (num % factor == 0) { 23 | count += 1; 24 | } 25 | factor += 1; 26 | } 27 | if (factor * factor > num) { 28 | return count * 2; 29 | } else { 30 | // perfect square 31 | return count * 2 + 1; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/012. Highly divisible triangular number/012.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | triangle := 0 7 | i := 1 8 | for { 9 | triangle += i 10 | if numOfFactors(triangle) > 500 { 11 | fmt.Println(triangle) 12 | break 13 | } 14 | i++ 15 | } 16 | } 17 | 18 | func numOfFactors(num int) int { 19 | n := 0 20 | factor := 1 21 | for factor * factor < num { 22 | if num % factor == 0 { 23 | n += 1 24 | } 25 | factor += 1 26 | } 27 | if factor * factor > num { 28 | return n * 2 29 | } else { 30 | // perfect square 31 | return n * 2 + 1 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/012. Highly divisible triangular number/012.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | 3 | public static void main(String[] args) { 4 | long triangle = 0; 5 | int i = 1; 6 | while (true) { 7 | triangle += i; 8 | if (numOfFactors(triangle) > 500) { 9 | System.out.println(triangle); 10 | break; 11 | } 12 | i++; 13 | } 14 | } 15 | 16 | public static int numOfFactors(long num) { 17 | int count = 0; 18 | long factor = 1; 19 | while (factor * factor < num)) { 20 | if (num % factor == 0) { 21 | count += 1; 22 | } 23 | factor += 1; 24 | } 25 | if (factor * factor > num) { 26 | return count * 2; 27 | } else { 28 | // perfect square 29 | return count * 2 + 1; 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/012. Highly divisible triangular number/012.lua: -------------------------------------------------------------------------------- 1 | function num_of_factors(num) 2 | local n = 0 3 | local factor = 1 4 | while factor * factor < num do 5 | if num % factor == 0 then 6 | n = n + 1 7 | end 8 | factor = factor + 1 9 | end 10 | if factor * factor > num then 11 | return n * 2 12 | else 13 | -- perfect square 14 | return n * 2 + 1 15 | end 16 | end 17 | 18 | triangle = 0 19 | for i = 1, math.huge do 20 | triangle = triangle + i 21 | if num_of_factors(triangle) > 500 then 22 | print(triangle) 23 | break 24 | end 25 | end 26 | -------------------------------------------------------------------------------- /src/012. Highly divisible triangular number/012.py: -------------------------------------------------------------------------------- 1 | def num_of_factors(num): 2 | n = 0 3 | factor = 1 4 | while factor * factor < num: 5 | if num % factor == 0: 6 | n += 1 7 | factor += 1 8 | if factor * factor > num: 9 | return n * 2 10 | else: 11 | # perfect square 12 | return n * 2 + 1 13 | 14 | triangle = 0 15 | i = 1 16 | while True: 17 | triangle += i 18 | if num_of_factors(triangle) > 500: 19 | print(triangle) 20 | break 21 | i += 1 22 | -------------------------------------------------------------------------------- /src/012. Highly divisible triangular number/012.rb: -------------------------------------------------------------------------------- 1 | require 'prime' 2 | 3 | class Integer 4 | def num_of_factors 5 | self.prime_division.map { |a| a[1] + 1 }.inject(:*) 6 | end 7 | end 8 | 9 | triangle = 1 10 | i = 2 11 | while true 12 | triangle += i 13 | if triangle.num_of_factors > 500 14 | puts triangle 15 | break 16 | end 17 | i += 1 18 | end 19 | -------------------------------------------------------------------------------- /src/013. Large sum/013.py: -------------------------------------------------------------------------------- 1 | with open('013.txt') as f: 2 | nums = [] 3 | for line in f: 4 | nums.append(int(line)) 5 | total = sum(nums) 6 | print(str(total)[0:10]) 7 | -------------------------------------------------------------------------------- /src/013. Large sum/013.rb: -------------------------------------------------------------------------------- 1 | str = IO.read('013.txt') 2 | puts str.lines.map(&:to_i).inject(:+).to_s[0 .. 9] 3 | -------------------------------------------------------------------------------- /src/014. Longest Collatz sequence/014.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int collatz(long long num); 4 | 5 | int main(void) { 6 | long long max_num = 1; 7 | long long max_collatz = 1; 8 | for (long long n = 1; n <= 1000000; ++n) { 9 | int result = collatz(n); 10 | if (result > max_collatz) { 11 | max_num = n; 12 | max_collatz = result; 13 | } 14 | } 15 | printf("%lld\n", max_num); 16 | } 17 | 18 | int collatz(long long num) { 19 | int i = 1; 20 | while (num != 1) { 21 | i += 1; 22 | if (num % 2 == 0) { 23 | num /= 2; 24 | } else { 25 | num = num * 3 + 1; 26 | } 27 | } 28 | return i; 29 | } 30 | -------------------------------------------------------------------------------- /src/014. Longest Collatz sequence/014.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int collatz(long long num); 4 | 5 | int main() { 6 | long long max_num = 1; 7 | long long max_collatz = 1; 8 | for (long long n = 1; n <= 1000000; ++n) { 9 | int result = collatz(n); 10 | if (result > max_collatz) { 11 | max_num = n; 12 | max_collatz = result; 13 | } 14 | } 15 | std::cout << max_num << std::endl; 16 | } 17 | 18 | int collatz(long long num) { 19 | int i = 1; 20 | while (num != 1) { 21 | i += 1; 22 | if (num % 2 == 0) { 23 | num /= 2; 24 | } else { 25 | num = num * 3 + 1; 26 | } 27 | } 28 | return i; 29 | } 30 | -------------------------------------------------------------------------------- /src/014. Longest Collatz sequence/014.hs: -------------------------------------------------------------------------------- 1 | import Data.List 2 | 3 | main = print $ snd $ foldl1' max [(collatz n, n) | n <- [1 .. 1000000]] 4 | 5 | collatz :: Integer -> Integer 6 | collatz 1 = 1 7 | collatz n 8 | | even n = collatz (n `div` 2) + 1 9 | | odd n = collatz (n * 3 + 1) + 1 10 | -------------------------------------------------------------------------------- /src/014. Longest Collatz sequence/014.lua: -------------------------------------------------------------------------------- 1 | function collatz(n) 2 | local ch = 1 3 | while n ~= 1 do 4 | if n % 2 == 0 then 5 | n = n / 2 6 | else 7 | n = n * 3 + 1 8 | end 9 | ch = ch + 1 10 | end 11 | return ch 12 | end 13 | 14 | local max = 0 15 | local res = 0 16 | for n = 1, 1000000 do 17 | ch = collatz(n) 18 | if ch > max then 19 | max = ch 20 | res = n 21 | end 22 | end 23 | 24 | print(res) 25 | -------------------------------------------------------------------------------- /src/014. Longest Collatz sequence/014.py: -------------------------------------------------------------------------------- 1 | def collatz(num): 2 | i = 1 3 | while num != 1: 4 | i += 1 5 | if num % 2 == 0: 6 | num /= 2 7 | else: 8 | num = num * 3 + 1 9 | return i 10 | 11 | max_num = 0 12 | max_collatz = 0 13 | for num in range(1, 1000001): 14 | result = collatz(num) 15 | if result > max_collatz: 16 | max_collatz = result 17 | max_num = num 18 | 19 | print(max_num) 20 | -------------------------------------------------------------------------------- /src/014. Longest Collatz sequence/014.rb: -------------------------------------------------------------------------------- 1 | def collatz(num) 2 | i = 1 3 | while num != 1 4 | i += 1 5 | num = case num.even? 6 | when true then num / 2 7 | when false then num * 3 + 1 8 | end 9 | end 10 | i 11 | end 12 | 13 | max_num = 0 14 | max_collatz = 0 15 | 1.upto(1000000) do |num| 16 | result = collatz(num) 17 | if result > max_collatz 18 | max_collatz = result 19 | max_num = num 20 | end 21 | end 22 | 23 | puts max_num 24 | -------------------------------------------------------------------------------- /src/015. Lattice paths/015.lua: -------------------------------------------------------------------------------- 1 | path = {} 2 | m = 0 3 | n = 0 4 | for m = 0, 20 do 5 | for n = m, 20 do 6 | print("path " .. m .. " " .. n) 7 | if m == 0 then 8 | path[m .. "_" .. n] = 1 9 | elseif m == n then 10 | path[m .. "_" .. n] = path[(m - 1) .. "_" .. n] * 2 11 | else 12 | path[m .. "_" .. n] = path[(m - 1) .. "_" .. n] + path[m .. "_" .. (n - 1)] 13 | end 14 | end 15 | end 16 | 17 | print(path[20 .. "_" .. 20]) -------------------------------------------------------------------------------- /src/015. Lattice paths/015.rb: -------------------------------------------------------------------------------- 1 | path = Hash.new(0) 2 | 0.upto(20) do |m| 3 | m.upto(20) do |n| 4 | path[(m.to_s + ':' + n.to_s).to_sym] = case m 5 | when 0 then 1 6 | when n then path[((m - 1).to_s + ':' + n.to_s).to_sym] * 2 7 | else path[((m - 1).to_s + ':' + n.to_s).to_sym] + path[(m.to_s + ':' + (n - 1).to_s).to_sym] 8 | end 9 | end 10 | end 11 | 12 | puts path[:"20:20"] -------------------------------------------------------------------------------- /src/016. Power digit sum/016.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "math/big" 6 | ) 7 | 8 | func main() { 9 | var power big.Int 10 | power.Exp(big.NewInt(2), big.NewInt(1000), nil) 11 | sumDigits := 0 12 | for _, char := range power.String() { 13 | digit := char - '0' 14 | sumDigits += int(digit) 15 | } 16 | fmt.Println(sumDigits) 17 | } 18 | -------------------------------------------------------------------------------- /src/016. Power digit sum/016.hs: -------------------------------------------------------------------------------- 1 | import Data.Char 2 | 3 | main = print $ sum $ map digitToInt . show $ 2 ^ 1000 4 | -------------------------------------------------------------------------------- /src/016. Power digit sum/016.java: -------------------------------------------------------------------------------- 1 | import java.math.*; 2 | 3 | public class Main { 4 | public static void main(String[] args) { 5 | BigInteger power = BigInteger.valueOf(2).pow(1000); 6 | byte[] arr = power.toString().getBytes(); 7 | int sum = 0; 8 | for (byte digit : arr) { 9 | sum += digit - '0'; 10 | } 11 | System.out.println(sum); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/016. Power digit sum/016.py: -------------------------------------------------------------------------------- 1 | print(sum(map(int, str(2 ** 1000)))) 2 | -------------------------------------------------------------------------------- /src/016. Power digit sum/016.rb: -------------------------------------------------------------------------------- 1 | puts (2 ** 1000).to_s.chars.map(&:to_i).inject(:+) -------------------------------------------------------------------------------- /src/017. Number letter counts/017.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define NUM_STR_LEN 256 5 | 6 | int main(void) { 7 | char n[1001][NUM_STR_LEN] = {""}; 8 | //strcpy(n[0], "zero"); 9 | strcpy(n[1], "one"); 10 | strcpy(n[2], "two"); 11 | strcpy(n[3], "three"); 12 | strcpy(n[4], "four"); 13 | strcpy(n[5], "five"); 14 | strcpy(n[6], "six"); 15 | strcpy(n[7], "seven"); 16 | strcpy(n[8], "eight"); 17 | strcpy(n[9], "nine"); 18 | strcpy(n[10], "ten"); 19 | strcpy(n[11], "eleven"); 20 | strcpy(n[12], "twelve"); 21 | strcpy(n[13], "thirteen"); 22 | strcpy(n[14], "fourteen"); 23 | strcpy(n[15], "fifteen"); 24 | strcpy(n[16], "sixteen"); 25 | strcpy(n[17], "seventeen"); 26 | strcpy(n[18], "eighteen"); 27 | strcpy(n[19], "nineteen"); 28 | 29 | strcpy(n[20], "twenty"); 30 | strcpy(n[30], "thirty"); 31 | strcpy(n[40], "forty"); 32 | strcpy(n[50], "fifty"); 33 | strcpy(n[60], "sixty"); 34 | strcpy(n[70], "seventy"); 35 | strcpy(n[80], "eighty"); 36 | strcpy(n[90], "ninety"); 37 | 38 | // generate 21-99 39 | for (int b = 2; b <= 9; ++b) { 40 | for (int a = 1; a <= 9; ++a) { 41 | strcpy(n[b * 10 + a], n[b * 10]); 42 | strcat(n[b * 10 + a], n[a]); 43 | } 44 | } 45 | 46 | for (int c = 1; c <= 9; ++c) { 47 | strcpy(n[c * 100], n[c]); 48 | strcat(n[c * 100], "hundred"); 49 | for (int ba = 1; ba <= 99; ++ba) { 50 | strcpy(n[c * 100 + ba], n[c * 100]); 51 | strcat(n[c * 100 + ba], "and"); 52 | strcat(n[c * 100 + ba], n[ba]); 53 | } 54 | } 55 | 56 | strcpy(n[1000], n[1]); 57 | strcat(n[1000], "thousand"); 58 | 59 | int sum = 0; 60 | for (int i = 1; i <= 1000; ++i) { 61 | sum += strlen(n[i]); 62 | } 63 | 64 | printf("%d\n", sum); 65 | } 66 | -------------------------------------------------------------------------------- /src/017. Number letter counts/017.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() { 5 | std::vector n(1001); 6 | //n[0] = "zero"; 7 | n[1] = "one"; 8 | n[2] = "two"; 9 | n[3] = "three"; 10 | n[4] = "four"; 11 | n[5] = "five"; 12 | n[6] = "six"; 13 | n[7] = "seven"; 14 | n[8] = "eight"; 15 | n[9] = "nine"; 16 | n[10] = "ten"; 17 | n[11] = "eleven"; 18 | n[12] = "twelve"; 19 | n[13] = "thirteen"; 20 | n[14] = "fourteen"; 21 | n[15] = "fifteen"; 22 | n[16] = "sixteen"; 23 | n[17] = "seventeen"; 24 | n[18] = "eighteen"; 25 | n[19] = "nineteen"; 26 | 27 | n[20] = "twenty"; 28 | n[30] = "thirty"; 29 | n[40] = "forty"; 30 | n[50] = "fifty"; 31 | n[60] = "sixty"; 32 | n[70] = "seventy"; 33 | n[80] = "eighty"; 34 | n[90] = "ninety"; 35 | 36 | // generate 21-99 37 | for (int b = 2; b <= 9; ++b) { 38 | for (int a = 1; a <= 9; ++a) { 39 | n[b * 10 + a] = n[b * 10] + n[a]; 40 | } 41 | } 42 | 43 | for (int c = 1; c <= 9; ++c) { 44 | n[c * 100] = n[c] + "hundred"; 45 | for (int ba = 1; ba <= 99; ++ba) { 46 | n[c * 100 + ba] = n[c * 100] + "and" + n[ba]; 47 | } 48 | } 49 | 50 | n[1000] = n[1] + "thousand"; 51 | 52 | int sum = 0; 53 | for (std::string s : n) { 54 | sum += s.size(); 55 | } 56 | 57 | std::cout << sum << std::endl; 58 | } 59 | -------------------------------------------------------------------------------- /src/017. Number letter counts/017.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | var n[1001] string 7 | //n[0] = "zero" 8 | n[1] = "one" 9 | n[2] = "two" 10 | n[3] = "three" 11 | n[4] = "four" 12 | n[5] = "five" 13 | n[6] = "six" 14 | n[7] = "seven" 15 | n[8] = "eight" 16 | n[9] = "nine" 17 | n[10] = "ten" 18 | n[11] = "eleven" 19 | n[12] = "twelve" 20 | n[13] = "thirteen" 21 | n[14] = "fourteen" 22 | n[15] = "fifteen" 23 | n[16] = "sixteen" 24 | n[17] = "seventeen" 25 | n[18] = "eighteen" 26 | n[19] = "nineteen" 27 | 28 | n[20] = "twenty" 29 | n[30] = "thirty" 30 | n[40] = "forty" 31 | n[50] = "fifty" 32 | n[60] = "sixty" 33 | n[70] = "seventy" 34 | n[80] = "eighty" 35 | n[90] = "ninety" 36 | 37 | // generate 21-99 38 | for b := 2; b <= 9; b++ { 39 | for a := 1; a <= 9; a++ { 40 | n[b * 10 + a] = n[b * 10] + n[a] 41 | } 42 | } 43 | 44 | for c := 1; c <= 9; c++ { 45 | n[c * 100] = n[c] + "hundred" 46 | for ba := 1; ba <= 99; ba++ { 47 | n[c * 100 + ba] = n[c * 100] + "and" + n[ba] 48 | } 49 | } 50 | 51 | n[1000] = n[1] + "thousand" 52 | 53 | sum := 0 54 | for _, s := range n { 55 | sum += len(s) 56 | } 57 | 58 | fmt.Println(sum) 59 | } 60 | -------------------------------------------------------------------------------- /src/017. Number letter counts/017.hs: -------------------------------------------------------------------------------- 1 | main = print $ sum $ map (length . numToWord) [1..1000] 2 | 3 | numToWord :: Int -> String 4 | numToWord num 5 | | num == 1 = "one" 6 | | num == 2 = "two" 7 | | num == 3 = "three" 8 | | num == 4 = "four" 9 | | num == 5 = "five" 10 | | num == 6 = "six" 11 | | num == 7 = "seven" 12 | | num == 8 = "eight" 13 | | num == 9 = "nine" 14 | | num == 10 = "ten" 15 | | num == 11 = "eleven" 16 | | num == 12 = "twelve" 17 | | num == 13 = "thirteen" 18 | | num == 14 = "fourteen" 19 | | num == 15 = "fifteen" 20 | | num == 16 = "sixteen" 21 | | num == 17 = "seventeen" 22 | | num == 18 = "eighteen" 23 | | num == 19 = "nineteen" 24 | | num == 20 = "twenty" 25 | | num == 30 = "thirty" 26 | | num == 40 = "forty" 27 | | num == 50 = "fifty" 28 | | num == 60 = "sixty" 29 | | num == 70 = "seventy" 30 | | num == 80 = "eighty" 31 | | num == 90 = "ninety" 32 | | num < 100 = (numToWord $ num - num `mod` 10) ++ (numToWord $ num `mod` 10) 33 | | num < 1000 && num `mod` 100 == 0 = (numToWord $ num `quot` 100) ++ "hundred" 34 | | num < 1000 = (numToWord $ num `quot` 100 * 100) ++ "and" ++ (numToWord $ num `mod` 100) 35 | | num == 1000 = numToWord 1 ++ "thousand" 36 | -------------------------------------------------------------------------------- /src/017. Number letter counts/017.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | public static void main(String[] args) { 3 | String[] n = new String[1001]; 4 | n[0] = ""; 5 | n[1] = "one"; 6 | n[2] = "two"; 7 | n[3] = "three"; 8 | n[4] = "four"; 9 | n[5] = "five"; 10 | n[6] = "six"; 11 | n[7] = "seven"; 12 | n[8] = "eight"; 13 | n[9] = "nine"; 14 | n[10] = "ten"; 15 | n[11] = "eleven"; 16 | n[12] = "twelve"; 17 | n[13] = "thirteen"; 18 | n[14] = "fourteen"; 19 | n[15] = "fifteen"; 20 | n[16] = "sixteen"; 21 | n[17] = "seventeen"; 22 | n[18] = "eighteen"; 23 | n[19] = "nineteen"; 24 | 25 | n[20] = "twenty"; 26 | n[30] = "thirty"; 27 | n[40] = "forty"; 28 | n[50] = "fifty"; 29 | n[60] = "sixty"; 30 | n[70] = "seventy"; 31 | n[80] = "eighty"; 32 | n[90] = "ninety"; 33 | 34 | // generate 21-99 35 | for (int b = 2; b <= 9; ++b) { 36 | for (int a = 1; a <= 9; ++a) { 37 | n[b * 10 + a] = n[b * 10] + n[a]; 38 | } 39 | } 40 | 41 | for (int c = 1; c <= 9; ++c) { 42 | n[c * 100] = n[c] + "hundred"; 43 | for (int ba = 1; ba <= 99; ++ba) { 44 | n[c * 100 + ba] = n[c * 100] + "and" + n[ba]; 45 | } 46 | } 47 | 48 | n[1000] = n[1] + "thousand"; 49 | 50 | int sum = 0; 51 | for (String s : n) { 52 | sum += s.length(); 53 | } 54 | 55 | System.out.println(sum); 56 | } 57 | 58 | } 59 | -------------------------------------------------------------------------------- /src/017. Number letter counts/017.lua: -------------------------------------------------------------------------------- 1 | local n = {} 2 | 3 | n[1] = 'one' 4 | n[2] = 'two' 5 | n[3] = 'three' 6 | n[4] = 'four' 7 | n[5] = 'five' 8 | n[6] = 'six' 9 | n[7] = 'seven' 10 | n[8] = 'eight' 11 | n[9] = 'nine' 12 | n[10] = 'ten' 13 | n[11] = 'eleven' 14 | n[12] = 'twelve' 15 | n[13] = 'thirteen' 16 | n[14] = 'fourteen' 17 | n[15] = 'fifteen' 18 | n[16] = 'sixteen' 19 | n[17] = 'seventeen' 20 | n[18] = 'eighteen' 21 | n[19] = 'nineteen' 22 | 23 | n[20] = 'twenty' 24 | n[30] = 'thirty' 25 | n[40] = 'forty' 26 | n[50] = 'fifty' 27 | n[60] = 'sixty' 28 | n[70] = 'seventy' 29 | n[80] = 'eighty' 30 | n[90] = 'ninety' 31 | 32 | -- generate 21-99 33 | for b = 2, 9 do 34 | for a = 1, 9 do 35 | n[b * 10 + a] = n[b * 10] .. n[a] 36 | end 37 | end 38 | 39 | for c = 1, 9 do 40 | n[c * 100] = n[c] .. 'hundred' 41 | for ba = 1, 99 do 42 | n[c * 100 + ba] = n[c * 100] .. 'and' .. n[ba] 43 | end 44 | end 45 | 46 | n[1000] = n[1] .. 'thousand' 47 | 48 | local sum = 0 49 | for _, v in ipairs(n) do 50 | sum = sum + v:len() 51 | end 52 | 53 | print(sum) 54 | -------------------------------------------------------------------------------- /src/017. Number letter counts/017.py: -------------------------------------------------------------------------------- 1 | n = [None] * 1001 2 | n[0] = 'zero' 3 | n[1] = 'one' 4 | n[2] = 'two' 5 | n[3] = 'three' 6 | n[4] = 'four' 7 | n[5] = 'five' 8 | n[6] = 'six' 9 | n[7] = 'seven' 10 | n[8] = 'eight' 11 | n[9] = 'nine' 12 | n[10] = 'ten' 13 | n[11] = 'eleven' 14 | n[12] = 'twelve' 15 | n[13] = 'thirteen' 16 | n[14] = 'fourteen' 17 | n[15] = 'fifteen' 18 | n[16] = 'sixteen' 19 | n[17] = 'seventeen' 20 | n[18] = 'eighteen' 21 | n[19] = 'nineteen' 22 | 23 | n[20] = 'twenty' 24 | n[30] = 'thirty' 25 | n[40] = 'forty' 26 | n[50] = 'fifty' 27 | n[60] = 'sixty' 28 | n[70] = 'seventy' 29 | n[80] = 'eighty' 30 | n[90] = 'ninety' 31 | 32 | # generate 21-99 33 | for b in range(2, 10): 34 | for a in range(1, 10): 35 | n[b * 10 + a] = n[b * 10] + n[a] 36 | 37 | for c in range(1, 10): 38 | n[c * 100] = n[c] + 'hundred' 39 | for ba in range(1, 100): 40 | n[c * 100 + ba] = n[c * 100] + 'and' + n[ba] 41 | 42 | n[1000] = n[1] + 'thousand' 43 | 44 | n.pop(0) # remove zero 45 | print(sum([len(num) for num in n])) 46 | -------------------------------------------------------------------------------- /src/017. Number letter counts/017.rb: -------------------------------------------------------------------------------- 1 | n = [] 2 | n[0] = 'zero' 3 | n[1] = 'one' 4 | n[2] = 'two' 5 | n[3] = 'three' 6 | n[4] = 'four' 7 | n[5] = 'five' 8 | n[6] = 'six' 9 | n[7] = 'seven' 10 | n[8] = 'eight' 11 | n[9] = 'nine' 12 | n[10] = 'ten' 13 | n[11] = 'eleven' 14 | n[12] = 'twelve' 15 | n[13] = 'thirteen' 16 | n[14] = 'fourteen' 17 | n[15] = 'fifteen' 18 | n[16] = 'sixteen' 19 | n[17] = 'seventeen' 20 | n[18] = 'eighteen' 21 | n[19] = 'nineteen' 22 | 23 | n[20] = 'twenty' 24 | n[30] = 'thirty' 25 | n[40] = 'forty' 26 | n[50] = 'fifty' 27 | n[60] = 'sixty' 28 | n[70] = 'seventy' 29 | n[80] = 'eighty' 30 | n[90] = 'ninety' 31 | 32 | # generate 21-99 33 | 2.upto(9) do |b| 34 | 1.upto(9) do |a| 35 | n[b * 10 + a] = n[b * 10] + n[a] 36 | end 37 | end 38 | 39 | 1.upto(9) do |c| 40 | n[c * 100] = n[c] + 'hundred' 41 | 1.upto(99) do |ba| 42 | n[c * 100 + ba] = n[c * 100] + 'and' + n[ba] 43 | end 44 | end 45 | 46 | n[1000] = n[1] + 'thousand' 47 | 48 | n.shift # remove zero 49 | puts n.map(&:length).inject(:+) 50 | -------------------------------------------------------------------------------- /src/018. Maximum path sum I/018.py: -------------------------------------------------------------------------------- 1 | triangle = [] 2 | with open('018.txt') as f: 3 | for line in f: 4 | triangle.append([int(n) for n in line.split()]) 5 | 6 | for row in range(1, len(triangle)): 7 | triangle[row - 1].append(0) 8 | for col in range(0, len(triangle[row])): 9 | triangle[row][col] += max(triangle[row - 1][col], triangle[row - 1][col - 1]) 10 | 11 | print(max(triangle[-1])) 12 | -------------------------------------------------------------------------------- /src/018. Maximum path sum I/018.rb: -------------------------------------------------------------------------------- 1 | file_content = IO.read('018.txt') 2 | 3 | triangle = [] 4 | file_content.lines do |line| 5 | triangle << line.split.map(&:to_i) 6 | end 7 | 8 | 1.upto(triangle.size - 1) do |row| 9 | triangle[row - 1] << 0 10 | 0.upto(triangle[row].size - 1) do |col| 11 | triangle[row][col] += [triangle[row - 1][col], triangle[row - 1][col - 1]].max 12 | end 13 | end 14 | 15 | puts triangle.last.max 16 | -------------------------------------------------------------------------------- /src/018. Maximum path sum I/018.txt: -------------------------------------------------------------------------------- 1 | 75 2 | 95 64 3 | 17 47 82 4 | 18 35 87 10 5 | 20 04 82 47 65 6 | 19 01 23 75 03 34 7 | 88 02 77 73 07 63 67 8 | 99 65 04 28 06 16 70 92 9 | 41 41 26 56 83 40 80 70 33 10 | 41 48 72 33 47 32 37 16 94 29 11 | 53 71 44 65 25 43 91 52 97 51 14 12 | 70 11 33 28 77 73 17 78 39 68 17 57 13 | 91 71 52 38 17 14 91 43 58 50 27 29 48 14 | 63 66 04 68 89 53 67 30 73 16 69 87 40 31 15 | 04 62 98 27 23 09 70 98 73 93 38 53 60 04 23 -------------------------------------------------------------------------------- /src/019. Counting Sundays/019.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "time" 6 | ) 7 | 8 | func main() { 9 | firstOfMonth := time.Date(1901, 1, 1, 0, 0, 0, 0, time.UTC) 10 | count := 0 11 | for firstOfMonth.Before(time.Date(2000, 12, 31, 0, 0, 0, 0, time.UTC)) { 12 | if firstOfMonth.Weekday() == time.Sunday { 13 | count += 1 14 | } 15 | firstOfMonth = firstOfMonth.AddDate(0, 1, 0) 16 | } 17 | fmt.Println(count) 18 | } 19 | -------------------------------------------------------------------------------- /src/019. Counting Sundays/019.java: -------------------------------------------------------------------------------- 1 | import java.time.DayOfWeek; 2 | import java.time.LocalDate; 3 | 4 | public class Main { 5 | public static void main(String[] args) { 6 | LocalDate firstOfMonth = LocalDate.of(1901, 1, 1); 7 | int count = 0; 8 | while (firstOfMonth.isBefore(LocalDate.of(2000, 12, 31))) { 9 | if (firstOfMonth.getDayOfWeek() == DayOfWeek.SUNDAY) { 10 | count += 1; 11 | } 12 | firstOfMonth = firstOfMonth.plusMonths(1); 13 | } 14 | System.out.println(count); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/019. Counting Sundays/019.py: -------------------------------------------------------------------------------- 1 | from datetime import date 2 | 3 | counter = 0 4 | for year in range(1901, 2001): 5 | for month in range(1, 13): 6 | d = date(year, month, 1) 7 | if d.weekday() == 6: 8 | counter += 1 9 | 10 | print(counter) 11 | -------------------------------------------------------------------------------- /src/019. Counting Sundays/019.rb: -------------------------------------------------------------------------------- 1 | require 'date' 2 | 3 | first_of_month = Date.new(1901, 1, 1) 4 | count = 0 5 | while first_of_month < Date.new(2000, 12, 31) 6 | count += 1 if first_of_month.sunday? 7 | first_of_month = first_of_month.next_month 8 | end 9 | 10 | puts count -------------------------------------------------------------------------------- /src/020. Factorial digit sum/020.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "math/big" 6 | ) 7 | 8 | func main () { 9 | factorial := *big.NewInt(1) 10 | for i := 1; i <= 100; i++ { 11 | factorial.Mul(&factorial, big.NewInt(int64(i))) 12 | } 13 | 14 | var sumDigits big.Int 15 | for factorial.Cmp(big.NewInt(0)) > 0 { 16 | var digit big.Int 17 | factorial.DivMod(&factorial, big.NewInt(10), &digit) 18 | sumDigits.Add(&sumDigits, &digit) 19 | } 20 | fmt.Println(sumDigits.String()) 21 | } 22 | -------------------------------------------------------------------------------- /src/020. Factorial digit sum/020.hs: -------------------------------------------------------------------------------- 1 | import Data.Char 2 | 3 | main = print $ sum $ map digitToInt $ show $ product [1 .. 100] 4 | -------------------------------------------------------------------------------- /src/020. Factorial digit sum/020.java: -------------------------------------------------------------------------------- 1 | import java.math.*; 2 | 3 | public class Main { 4 | public static void main(String[] args) { 5 | BigInteger factorial = BigInteger.ONE; 6 | for (int i = 1; i <= 100; i++) { 7 | factorial = factorial.multiply(BigInteger.valueOf(i)); 8 | } 9 | BigInteger sumDigits = BigInteger.ZERO; 10 | while (factorial.compareTo(BigInteger.ZERO) > 0){ 11 | sumDigits = sumDigits.add(factorial.mod(BigInteger.TEN)); 12 | factorial = factorial.divide(BigInteger.TEN); 13 | } 14 | System.out.println(sumDigits); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/020. Factorial digit sum/020.py: -------------------------------------------------------------------------------- 1 | from functools import reduce 2 | import operator 3 | 4 | factorial = reduce(operator.mul, range(1, 101)) 5 | print(sum([int(c) for c in str(factorial)])) 6 | -------------------------------------------------------------------------------- /src/020. Factorial digit sum/020.rb: -------------------------------------------------------------------------------- 1 | puts (1 .. 100).inject(:*).to_s.chars.map(&:to_i).inject(:+) 2 | -------------------------------------------------------------------------------- /src/021. Amicable numbers/021.rb: -------------------------------------------------------------------------------- 1 | def d(num) 2 | divisors = [] 3 | 1.upto(Integer(Math.sqrt(num))) do |n| 4 | if num % n == 0 5 | divisors << n 6 | if num / n != n and n != 1 7 | divisors << num / n 8 | end 9 | end 10 | end 11 | divisors.inject(:+) 12 | end 13 | 14 | amicable = [] 15 | 1.upto(10000) do |num| 16 | amicable << num if d(d(num)) == num and d(num) != num 17 | end 18 | 19 | puts amicable.inject(:+) -------------------------------------------------------------------------------- /src/022. Names scores/022.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using std::string; 8 | int score(string name); 9 | 10 | int main() { 11 | std::ifstream f("p022_names.txt"); 12 | string line; 13 | std::vector names; 14 | while (std::getline(f, line, ',')) { 15 | // remove first and last characters, which are the quote characters 16 | string name = line.substr(1, line.size() - 2); 17 | names.push_back(name); 18 | } 19 | std::sort(names.begin(), names.end()); 20 | int total = 0; 21 | int index = 1; 22 | for (string name : names) { 23 | total += index * score(name); 24 | ++index; 25 | } 26 | std::cout << total << std::endl; 27 | } 28 | 29 | int score(string name) { 30 | int total = 0; 31 | for (char c : name) { 32 | total += c - 'A' + 1; 33 | } 34 | return total; 35 | } 36 | -------------------------------------------------------------------------------- /src/022. Names scores/022.lua: -------------------------------------------------------------------------------- 1 | function score(name) 2 | total = 0 3 | for c in name:gmatch("%u") do 4 | total = total + c:byte() - string.byte('A') + 1 5 | end 6 | return total 7 | end 8 | 9 | local f = io.open("p022_names.txt") 10 | local all_names = f:read() 11 | local names = {} 12 | for name in all_names:gmatch('"(%u+)"') do 13 | table.insert(names, name) 14 | end 15 | table.sort(names) 16 | total_score = 0 17 | for index, name in ipairs(names) do 18 | total_score = total_score + index * score(name) 19 | end 20 | print(total_score) 21 | -------------------------------------------------------------------------------- /src/022. Names scores/022.rb: -------------------------------------------------------------------------------- 1 | def score(name) 2 | name.chars.map { |c| c.ord - 'A'.ord + 1 }.inject(:+) 3 | end 4 | 5 | File.open('p022_names.txt') do |file| 6 | all_names = file.read 7 | names = all_names.scan(/[^,"]+/) 8 | names.sort! 9 | total_score = 0 10 | names.each_with_index do |name, index| 11 | total_score += score(name) * (index + 1) 12 | end 13 | puts total_score 14 | end 15 | -------------------------------------------------------------------------------- /src/023. Non-abundant sums/023.rb: -------------------------------------------------------------------------------- 1 | require 'set' 2 | 3 | def sum_of_divisors(num) 4 | sum = 0 5 | 2.upto(Math.sqrt(num)) do |d| 6 | if num % d == 0 7 | sum += d 8 | sum += num / d unless d * d == num 9 | end 10 | end 11 | sum + 1 12 | end 13 | 14 | class Integer 15 | def abundant? 16 | sum_of_divisors(self) > self 17 | end 18 | end 19 | 20 | all_abundant = [] 21 | 1.upto(28123) do |n| 22 | all_abundant << n if n.abundant? 23 | end 24 | 25 | sum_of_two_abundants = Set.new 26 | all_abundant.each do |n1| 27 | all_abundant.each do |n2| 28 | sum_of_two_abundants.add(n1 + n2) if n1 + n2 <= 28123 29 | end 30 | end 31 | 32 | sum = 0 33 | 1.upto(28123) do |n| 34 | sum += n unless sum_of_two_abundants.include? n 35 | end 36 | 37 | puts sum 38 | -------------------------------------------------------------------------------- /src/024. Lexicographic permutations/024.py: -------------------------------------------------------------------------------- 1 | from itertools import permutations 2 | 3 | print(''.join([str(d) for d in list(permutations(range(0, 10)))[999999]])) 4 | -------------------------------------------------------------------------------- /src/024. Lexicographic permutations/024.rb: -------------------------------------------------------------------------------- 1 | puts (0 .. 9).to_a.permutation.to_a[999_999].join 2 | -------------------------------------------------------------------------------- /src/025. 1000-digit Fibonacci number/025.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "math/big" 6 | ) 7 | 8 | func main() { 9 | index := 1 10 | fa, fb := big.NewInt(1), big.NewInt(1) 11 | var upperLimit big.Int 12 | upperLimit.Exp(big.NewInt(10), big.NewInt(999), nil) 13 | for fa.Cmp(&upperLimit) < 0 { 14 | var temp big.Int 15 | temp.Set(fb) 16 | fb.Add(fa, fb) 17 | fa.Set(&temp) 18 | index++ 19 | } 20 | fmt.Println(index) 21 | } 22 | -------------------------------------------------------------------------------- /src/025. 1000-digit Fibonacci number/025.java: -------------------------------------------------------------------------------- 1 | import java.math.*; 2 | 3 | public class Main { 4 | 5 | public static void main(String[] args) { 6 | BigInteger fa = BigInteger.ONE; 7 | BigInteger fb = BigInteger.ONE; 8 | 9 | int index = 1; 10 | while (fa.toString().length() < 1000) { 11 | BigInteger temp = fb; 12 | fb = fa.add(fb); 13 | fa = temp; 14 | index++; 15 | } 16 | System.out.println(index); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/025. 1000-digit Fibonacci number/025.py: -------------------------------------------------------------------------------- 1 | index, fa, fb = 1, 1, 1 2 | while fa < 10 ** 999: 3 | fa, fb, index = fb, fa + fb, index + 1 4 | 5 | print(index) 6 | -------------------------------------------------------------------------------- /src/025. 1000-digit Fibonacci number/025.rb: -------------------------------------------------------------------------------- 1 | index, fa, fb = 1, 1, 1 2 | fa, fb, index = fb, fa + fb, index + 1 until fa > 10 ** 999 3 | puts index 4 | -------------------------------------------------------------------------------- /src/026. Reciprocal cycles/026.lua: -------------------------------------------------------------------------------- 1 | function fracCycle(n) 2 | local r = 1 3 | local fract = {} 4 | while r ~= 0 do 5 | while r < n do 6 | r = r * 10 7 | end 8 | r = r % n 9 | if r == 0 then 10 | return 0 11 | elseif fract[r] == true then 12 | local len = 0 13 | for i = 1, 1000 do 14 | if fract[i] == true then 15 | len = len + 1 16 | end 17 | end 18 | if n >= 100 then 19 | len = len * 3 20 | elseif n >= 10 then 21 | len = len * 2 22 | end 23 | return len 24 | else 25 | fract[r] = true 26 | end 27 | end 28 | end 29 | 30 | local max = 0 31 | local maxNum = 0 32 | for i = 1, 1000 do 33 | local c = fracCycle(i) 34 | if c > max then 35 | max = c 36 | maxNum = i 37 | end 38 | end 39 | 40 | print(maxNum) -------------------------------------------------------------------------------- /src/026. Reciprocal cycles/026.rb: -------------------------------------------------------------------------------- 1 | class Integer 2 | def fracCycle 3 | num = self 4 | num /= 2 while num % 2 == 0 5 | num /= 5 while num % 5 == 0 6 | return 0 if num == 1 7 | 8 | cycle = 1 9 | cycle += 1 while ('9' * cycle).to_i % num != 0 10 | cycle 11 | end 12 | end 13 | 14 | max = 1 15 | max_cycle = 0 16 | 1.upto(1000) do |n| 17 | if n.fracCycle > max_cycle 18 | max, max_cycle = n, n.fracCycle 19 | end 20 | end 21 | 22 | puts max 23 | -------------------------------------------------------------------------------- /src/027. Quadratic primes/027.rb: -------------------------------------------------------------------------------- 1 | require 'prime' 2 | 3 | max = 0 4 | result = [] 5 | (-999).upto(999) do |a| 6 | (-999).upto(999) do |b| 7 | n = 0 8 | begin 9 | q = n * n + a * n + b 10 | n += 1 11 | end while Prime.prime? q 12 | if n > max 13 | max = n 14 | result = [a, b] 15 | end 16 | end 17 | end 18 | 19 | puts result.inject(:*) -------------------------------------------------------------------------------- /src/028. Number spiral diagonals/028.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main(void) { 4 | int sum = 1; 5 | int n = 1; 6 | int step = 2; 7 | while (n < 1001 * 1001) { 8 | for (int i = 0; i < 4; ++i) { 9 | n += step; 10 | sum += n; 11 | } 12 | step += 2; 13 | } 14 | printf("%d\n", sum); 15 | } 16 | -------------------------------------------------------------------------------- /src/028. Number spiral diagonals/028.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() { 4 | int sum = 1; 5 | int n = 1; 6 | int step = 2; 7 | while (n < 1001 * 1001) { 8 | for (int i = 0; i < 4; ++i) { 9 | n += step; 10 | sum += n; 11 | } 12 | step += 2; 13 | } 14 | std::cout << sum << std::endl; 15 | } 16 | -------------------------------------------------------------------------------- /src/028. Number spiral diagonals/028.lua: -------------------------------------------------------------------------------- 1 | local sum = 1 2 | local n = 1 3 | local step = 2 4 | while n < 1001 * 1001 do 5 | for i = 1, 4 do 6 | n = n + step 7 | sum = sum + n 8 | end 9 | step = step + 2 10 | end 11 | 12 | print(sum) -------------------------------------------------------------------------------- /src/029. Distinct powers/029.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "math/big" 6 | ) 7 | 8 | func main() { 9 | result := make(map[string]bool) 10 | for a := int64(2); a <= 100; a++ { 11 | for b := int64(2); b <= 100; b++ { 12 | var power big.Int 13 | power.Exp(big.NewInt(a), big.NewInt(b), nil) 14 | result[power.String()] = true 15 | } 16 | } 17 | fmt.Println(len(result)) 18 | } 19 | -------------------------------------------------------------------------------- /src/029. Distinct powers/029.hs: -------------------------------------------------------------------------------- 1 | import Data.List 2 | 3 | main = print $ length $ nub [a^b | a<-[2 .. 100], b <- [2 .. 100]] 4 | -------------------------------------------------------------------------------- /src/029. Distinct powers/029.java: -------------------------------------------------------------------------------- 1 | import java.math.BigInteger; 2 | import java.util.HashSet; 3 | import java.util.Set; 4 | 5 | public class Main { 6 | public static void main(String[] args) { 7 | Set nums = new HashSet<>(); 8 | for (int a = 2; a <= 100; a++) { 9 | for (int b = 2; b <= 100; b++) { 10 | nums.add(BigInteger.valueOf(a).pow(b)); 11 | } 12 | } 13 | 14 | System.out.println(nums.size()); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/029. Distinct powers/029.py: -------------------------------------------------------------------------------- 1 | nums = {a ** b for a in range(2, 101) for b in range(2, 101)} 2 | print(len(nums)) 3 | -------------------------------------------------------------------------------- /src/029. Distinct powers/029.rb: -------------------------------------------------------------------------------- 1 | nums = [] 2 | 3 | 2.upto(100) do |a| 4 | 2.upto(100) do |b| 5 | nums << a ** b 6 | end 7 | end 8 | 9 | puts nums.uniq.size -------------------------------------------------------------------------------- /src/030. Digit fifth powers/030.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | static int digit_fifth_power_sum(int n); 4 | 5 | int main() { 6 | int sum = 0; 7 | for (int i = 2; i < 1000000; i++) { 8 | if (digit_fifth_power_sum(i) == i) { 9 | sum += i; 10 | } 11 | } 12 | printf("%d\n", sum); 13 | } 14 | 15 | static int digit_fifth_power_sum(int n) { 16 | int sum = 0; 17 | while (n > 0) { 18 | int d = n % 10; 19 | sum += d * d * d * d * d; 20 | n /= 10; 21 | } 22 | return sum; 23 | } 24 | -------------------------------------------------------------------------------- /src/030. Digit fifth powers/030.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | static int digit_fifth_power_sum(int n); 4 | 5 | int main() { 6 | int sum = 0; 7 | for (int i = 2; i < 1000000; i++) { 8 | if (digit_fifth_power_sum(i) == i) { 9 | sum += i; 10 | } 11 | } 12 | std::cout << sum << std::endl; 13 | } 14 | 15 | static int digit_fifth_power_sum(int n) { 16 | int sum = 0; 17 | while (n > 0) { 18 | int d = n % 10; 19 | sum += d * d * d * d * d; 20 | n /= 10; 21 | } 22 | return sum; 23 | } 24 | -------------------------------------------------------------------------------- /src/030. Digit fifth powers/030.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | sum := 0 7 | for i:= 2; i < 1000000; i++ { 8 | if digitFifthPowerSum(i) == i { 9 | sum += i 10 | } 11 | } 12 | fmt.Println(sum) 13 | } 14 | 15 | func digitFifthPowerSum(n int) int { 16 | sum := 0 17 | for n > 0 { 18 | d := n % 10 19 | sum += d * d * d * d * d 20 | n /= 10 21 | } 22 | return sum 23 | } 24 | -------------------------------------------------------------------------------- /src/030. Digit fifth powers/030.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | 3 | public static void main(String[] args) { 4 | 5 | int sum = 0; 6 | for (int i = 2; i < 1000000; i++) { 7 | if (digitFifthPowerSum(i) == i) { 8 | sum += i; 9 | } 10 | } 11 | System.out.println(sum); 12 | } 13 | 14 | private static int digitFifthPowerSum(int n) { 15 | int sum = 0; 16 | while (n > 0) { 17 | int d = n % 10; 18 | sum += d * d * d * d * d; 19 | n /= 10; 20 | } 21 | return sum; 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /src/030. Digit fifth powers/030.py: -------------------------------------------------------------------------------- 1 | def sum_of_fifth_power(num): 2 | sum = 0 3 | while num > 0: 4 | sum += (num % 10) ** 5 5 | num /= 10 6 | return sum 7 | 8 | result = [] 9 | for num in range(2, 1000000): 10 | if sum_of_fifth_power(num) == num: 11 | result.append(num) 12 | 13 | print(sum(result)) 14 | -------------------------------------------------------------------------------- /src/030. Digit fifth powers/030.rb: -------------------------------------------------------------------------------- 1 | def sum_of_fifth_power(num) 2 | sum = 0 3 | while num > 0 4 | sum += (num % 10) ** 5 5 | num /= 10 6 | end 7 | sum 8 | end 9 | 10 | result = [] 11 | 2.upto(999999) do |num| 12 | result << num if sum_of_fifth_power(num) == num 13 | end 14 | 15 | puts result.inject(:+) -------------------------------------------------------------------------------- /src/031. Coin sums/031.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | coins := []int{1, 2, 5, 10, 20, 50, 100, 200} 7 | amount := 200 8 | ways := make([]int, amount + 1) 9 | ways[0] = 1 10 | for _, coin := range coins { 11 | for n := coin; n <= amount; n++ { 12 | ways[n] += ways[n - coin] 13 | } 14 | } 15 | fmt.Println(ways[amount]) 16 | } 17 | -------------------------------------------------------------------------------- /src/031. Coin sums/031.lua: -------------------------------------------------------------------------------- 1 | local coins = {1, 2, 5, 10, 20, 50, 100, 200} 2 | local amount = 200 3 | local ways = {} 4 | for i = 0, amount + 1 do 5 | ways[i] = 0 6 | end 7 | ways[0] = 1 8 | for _, coin in ipairs(coins) do 9 | for n = coin, amount + 1 do 10 | ways[n] = ways[n] + ways[n - coin] 11 | end 12 | end 13 | 14 | print(ways[amount]) 15 | -------------------------------------------------------------------------------- /src/031. Coin sums/031.py: -------------------------------------------------------------------------------- 1 | coins = [1, 2, 5, 10, 20, 50, 100, 200] 2 | amount = 200 3 | ways = [0] * (amount + 1) 4 | ways[0] = 1 5 | for coin in coins: 6 | for n in range(coin, amount + 1): 7 | ways[n] += ways[n - coin] 8 | 9 | print(ways[amount]) 10 | -------------------------------------------------------------------------------- /src/031. Coin sums/031.rb: -------------------------------------------------------------------------------- 1 | coins = [1, 2, 5, 10, 20, 50, 100, 200] 2 | amount = 200 3 | ways = [0] * (amount + 1) 4 | ways[0] = 1 5 | coins.each do |coin| 6 | coin.upto(amount) do |n| 7 | ways[n] += ways[n - coin] 8 | end 9 | end 10 | 11 | puts ways[amount] 12 | -------------------------------------------------------------------------------- /src/032. Pandigital products/032.rb: -------------------------------------------------------------------------------- 1 | def pandigital(s) 2 | return false if s.size != 9 3 | s.chars.sort.join == '123456789' 4 | end 5 | 6 | result = [] 7 | 1.upto(99) do |a| 8 | 10.upto(9999) do |b| 9 | c = a * b 10 | if pandigital(a.to_s + b.to_s + c.to_s) 11 | result << c 12 | end 13 | end 14 | end 15 | 16 | puts result.uniq.inject(:+) -------------------------------------------------------------------------------- /src/033. Digit cancelling fractions/033.py: -------------------------------------------------------------------------------- 1 | from fractions import Fraction 2 | from functools import reduce 3 | 4 | result = [] 5 | 6 | # a / b 7 | for a in range(10, 100): 8 | for b in range(a + 1, 100): 9 | a1 = a // 10 10 | a2 = a % 10 11 | b1 = b // 10 12 | b2 = b % 10 13 | if b2 != 0 and Fraction(a, b) == Fraction(a1, b2) and a2 == b1: 14 | result.append(Fraction(a, b)) 15 | 16 | print(reduce(lambda a, b: a * b, result).denominator) 17 | -------------------------------------------------------------------------------- /src/033. Digit cancelling fractions/033.rb: -------------------------------------------------------------------------------- 1 | result = [] 2 | 3 | # a / b 4 | 10.upto(99) do |a| 5 | (a + 1).upto(99) do |b| 6 | a1 = a / 10 7 | a2 = a % 10 8 | b1 = b / 10 9 | b2 = b % 10 10 | next if b2 == 0 11 | if Rational(a, b) == Rational(a1, b2) and a2 == b1 12 | result << Rational(a, b) 13 | end 14 | end 15 | end 16 | 17 | puts result.inject(&:*).denominator 18 | -------------------------------------------------------------------------------- /src/034. Digit factorials/034.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | long long factorial[10]; 4 | void init_factorial(); 5 | long long digit_fact(long long n); 6 | 7 | int main(void) { 8 | init_factorial(); 9 | // estimated upper limit, because 9! * 6 < 999999 10 | long long upper_limit = 999999; 11 | long long total = 0; 12 | for (long long n = 10; n <= upper_limit; ++n) { 13 | if (n == digit_fact(n)) { 14 | total += n; 15 | } 16 | } 17 | printf("%lld\n", total); 18 | } 19 | 20 | void init_factorial() { 21 | factorial[0] = 1; 22 | for (int d = 1; d <= 9; ++d) { 23 | factorial[d] = factorial[d - 1] * d; 24 | } 25 | } 26 | 27 | long long digit_fact(long long n) { 28 | long long sum = 0; 29 | while (n > 0) { 30 | sum += factorial[n % 10]; 31 | n /= 10; 32 | } 33 | return sum; 34 | } 35 | -------------------------------------------------------------------------------- /src/034. Digit factorials/034.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | std::vector factorial; 5 | void init_factorial(); 6 | long long digit_fact(long long n); 7 | 8 | int main() { 9 | init_factorial(); 10 | // estimated upper limit, because 9! * 6 < 999999 11 | long long upper_limit = 999999; 12 | long long total = 0; 13 | for (long long n = 10; n <= upper_limit; ++n) { 14 | if (n == digit_fact(n)) { 15 | total += n; 16 | } 17 | } 18 | std::cout << total << std::endl; 19 | } 20 | 21 | void init_factorial() { 22 | factorial.push_back(1); 23 | for (long long d = 1; d <= 9; ++d) { 24 | factorial.push_back(factorial[d - 1] * d); 25 | } 26 | } 27 | 28 | long long digit_fact(long long n) { 29 | long long sum = 0; 30 | while (n > 0) { 31 | sum += factorial[n % 10]; 32 | n /= 10; 33 | } 34 | return sum; 35 | } 36 | -------------------------------------------------------------------------------- /src/034. Digit factorials/034.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | var factorials [10]int 6 | 7 | func init() { 8 | factorials[0] = 1 9 | for i := 1; i <= 9; i++ { 10 | factorials[i] = factorials[i - 1] * i 11 | } 12 | } 13 | 14 | func main() { 15 | // estimated upper limist, because 9! * 6 < 999999 16 | const upperLimit = 999999 17 | sum := 0 18 | for i := 10; i <= upperLimit; i++ { 19 | if i == digitFactorial(i) { 20 | sum += i 21 | } 22 | } 23 | fmt.Println(sum) 24 | } 25 | 26 | func digitFactorial(n int) int { 27 | sum := 0 28 | for n > 0 { 29 | sum += factorials[n % 10] 30 | n /= 10 31 | } 32 | return sum 33 | } 34 | -------------------------------------------------------------------------------- /src/034. Digit factorials/034.lua: -------------------------------------------------------------------------------- 1 | local factorial = {[0] = 1} 2 | for d = 1, 9 do 3 | factorial[d] = factorial[d - 1] * d 4 | end 5 | 6 | function digit_fact(n) 7 | local sum = 0 8 | while n > 0 do 9 | sum = sum + factorial[n % 10] 10 | n = math.floor(n / 10) 11 | end 12 | return sum 13 | end 14 | 15 | local total = 0 16 | -- estimated upper limist, because 9! * 6 < 999999 17 | local upper_limit = 999999 18 | for n = 10, upper_limit do 19 | if n == digit_fact(n) then 20 | total = total + n 21 | end 22 | end 23 | print(total) 24 | -------------------------------------------------------------------------------- /src/034. Digit factorials/034.py: -------------------------------------------------------------------------------- 1 | factorial = [1] 2 | for d in range(1, 10): 3 | factorial.append(factorial[-1] * d) 4 | 5 | def digit_fact(n): 6 | return sum([factorial[int(d)] for d in str(n)]) 7 | 8 | total = 0 9 | # estimated upper limist, because 9! * 6 < 999999 10 | upper_limit = 999999 11 | for n in range(10, upper_limit): 12 | if n == digit_fact(n): 13 | total += n 14 | print(total) 15 | -------------------------------------------------------------------------------- /src/034. Digit factorials/034.rb: -------------------------------------------------------------------------------- 1 | $factorials = [1] # 0! 2 | 1.upto(9) do |d| 3 | $factorials[d] = d * $factorials[d - 1] 4 | end 5 | 6 | def sum_of_digit_factorials(num) 7 | num.to_s.chars.map(&:to_i).map { |d| $factorials[d] }.inject(:+) 8 | end 9 | 10 | class Integer 11 | def curious? 12 | self == sum_of_digit_factorials(self) 13 | end 14 | end 15 | 16 | total = 0 17 | # estimated upper limist, because 9! * 6 < 999999 18 | upper_limit = 999_999 19 | 10.upto(upper_limit) do |n| 20 | total += n if n.curious? 21 | end 22 | puts total 23 | -------------------------------------------------------------------------------- /src/035. Circular primes/035.rb: -------------------------------------------------------------------------------- 1 | require 'prime' 2 | require 'set' 3 | 4 | primes = [] 5 | Prime.each(1_000_000) { |p| primes << p } 6 | set_of_primes = primes.to_set 7 | 8 | circular_primes = [2, 5] 9 | primes.each do |p| 10 | chars = p.to_s.chars 11 | next if chars.any? { |c| '024685'.include? c } 12 | if (1 ... chars.size).all? { |d| set_of_primes.include? chars.rotate(d).join.to_i } 13 | circular_primes << p 14 | end 15 | end 16 | 17 | puts circular_primes.size 18 | -------------------------------------------------------------------------------- /src/036. Double-base palindromes/036.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "strings" 6 | ) 7 | 8 | func main() { 9 | sum := 0 10 | for i := 1; i < 1000000; i++ { 11 | if isPalindrome(toBase10(i)) && isPalindrome(toBase2(i)) { 12 | sum += i 13 | } 14 | } 15 | fmt.Println(sum) 16 | } 17 | 18 | func isPalindrome(s string) bool { 19 | chars := strings.Split(s, "") 20 | for i, j := 0, len(chars) - 1; i < j; i, j = i + 1, j - 1 { 21 | chars[i], chars[j] = chars[j], chars[i] 22 | } 23 | reversed := strings.Join(chars, "") 24 | return s == reversed 25 | } 26 | 27 | func toBase10(n int) string { 28 | return fmt.Sprintf("%d", n) 29 | } 30 | 31 | func toBase2(n int) string { 32 | return fmt.Sprintf("%b", n) 33 | } 34 | -------------------------------------------------------------------------------- /src/036. Double-base palindromes/036.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | 3 | public static void main(String[] args) { 4 | long sum = 0; 5 | for (long n = 0; n <= 1_000_000; n++) { 6 | if (isPalindrome(Long.toString(n)) && isPalindrome(Long.toString(n, 2))) { 7 | sum += n; 8 | } 9 | } 10 | System.out.println(sum); 11 | } 12 | 13 | private static boolean isPalindrome(String s) { 14 | return reverseString(s).equals(s); 15 | } 16 | 17 | private static String reverseString(String original) { 18 | return new StringBuilder(original).reverse().toString(); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/036. Double-base palindromes/036.lua: -------------------------------------------------------------------------------- 1 | function bin_str(n) 2 | local str = "" 3 | while n ~= 0 do 4 | str = tostring(n % 2) .. str 5 | n = math.floor(n / 2) 6 | end 7 | return str 8 | end 9 | 10 | function is_palindrome(str) 11 | for i = 1, #str / 2 do 12 | if string.byte(str, i) ~= string.byte(str, -i) then 13 | return false 14 | end 15 | end 16 | return true 17 | end 18 | 19 | local sum = 0 20 | 21 | for i = 1, 1000000 do 22 | if is_palindrome(tostring(i)) and is_palindrome(bin_str(i)) then 23 | sum = sum + i 24 | end 25 | end 26 | 27 | print(sum) -------------------------------------------------------------------------------- /src/036. Double-base palindromes/036.rb: -------------------------------------------------------------------------------- 1 | class Integer 2 | def palindrome_dec? 3 | decimal = self.to_s 4 | decimal == decimal.reverse 5 | end 6 | 7 | def palindrome_bin? 8 | binary = self.to_s(2) 9 | binary == binary.reverse 10 | end 11 | end 12 | 13 | puts (1 .. 1_000_000).to_a.keep_if(&:palindrome_dec?).keep_if(&:palindrome_bin?).inject(:+) 14 | -------------------------------------------------------------------------------- /src/037. Truncatable primes/037.rb: -------------------------------------------------------------------------------- 1 | require 'prime' 2 | 3 | class Integer 4 | def scan_left 5 | left = [] 6 | d = 1 7 | while self > 10 ** d 8 | left << self % 10 ** d 9 | d += 1 10 | end 11 | left 12 | end 13 | 14 | def scan_right 15 | n = self 16 | right = [] 17 | while n > 10 18 | n = n / 10 19 | right << n 20 | end 21 | right 22 | end 23 | end 24 | 25 | truncatable = [] 26 | Prime.each do |p| 27 | if p.prime? and p.scan_left.all?(&:prime?) and p.scan_right.all?(&:prime?) 28 | truncatable << p if p > 10 29 | break if truncatable.size == 11 30 | end 31 | end 32 | 33 | puts truncatable.inject(:+) 34 | -------------------------------------------------------------------------------- /src/038. Pandigital multiples/038.rb: -------------------------------------------------------------------------------- 1 | require 'set' 2 | 3 | def form_pandigital(num) 4 | pandigital_str = '' 5 | digits = Set.new 6 | n = 1 7 | while digits.size < 9 8 | m = num * n 9 | while m > 0 10 | m, d = m.divmod(10) 11 | return nil if d == 0 12 | if digits.include? d 13 | return nil 14 | else 15 | digits.add(d) 16 | end 17 | end 18 | pandigital_str += (num * n).to_s 19 | n += 1 20 | end 21 | return pandigital_str.to_i 22 | end 23 | 24 | max_pandigital = 0 25 | 1.upto(9999) do |n| 26 | candidate = form_pandigital(n) 27 | if candidate != nil and candidate > max_pandigital 28 | max_pandigital = candidate 29 | end 30 | end 31 | 32 | puts max_pandigital 33 | -------------------------------------------------------------------------------- /src/039. Integer right triangles/039.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "math" 6 | ) 7 | 8 | func main() { 9 | counter := make(map[int]int) 10 | for a := 1; a <= 1000 / 3; a++ { 11 | for b := a; b <= 1000 / 2; b++ { 12 | c := math.Sqrt(float64(a) * float64(a) + float64(b) * float64(b)) 13 | if c == float64(int(c)) { 14 | p := a + b + int(c) 15 | if p > 1000 { 16 | break 17 | } 18 | counter[p]++ 19 | } 20 | } 21 | } 22 | 23 | maxP, maxCount := 0, 0 24 | for p, count := range counter { 25 | if count > maxCount { 26 | maxP, maxCount = p, count 27 | } 28 | } 29 | fmt.Println(maxP) 30 | } 31 | -------------------------------------------------------------------------------- /src/040. Champernowne's constant/040.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() { 5 | std::string d; 6 | int i = 0; 7 | do { 8 | d += std::to_string(i); 9 | ++i; 10 | } while (d.size() <= 1000000); 11 | int product = 1; 12 | for (i = 1; i <= 1000000; i *= 10) { 13 | product *= d[i] - '0'; 14 | } 15 | std::cout << product << std::endl; 16 | } 17 | -------------------------------------------------------------------------------- /src/040. Champernowne's constant/040.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "strconv" 6 | ) 7 | 8 | func main() { 9 | s := "" 10 | n := 0 11 | for len(s) <= 1000000 { 12 | s += strconv.Itoa(n) 13 | n++ 14 | } 15 | prod := 1 16 | for i := 1; i <= 1000000; i *= 10 { 17 | prod *= int(s[i]) - '0' 18 | } 19 | fmt.Println(prod) 20 | } 21 | -------------------------------------------------------------------------------- /src/040. Champernowne's constant/040.hs: -------------------------------------------------------------------------------- 1 | import Data.Char 2 | 3 | main = print result 4 | 5 | getDigit :: String -> Int -> Int 6 | getDigit d n = digitToInt $ d !! (n - 1) 7 | 8 | d = concat $ take 200000 $ map show [1..] 9 | result = getDigit d 1 * 10 | getDigit d 10 * 11 | getDigit d 100 * 12 | getDigit d 1000 * 13 | getDigit d 10000 * 14 | getDigit d 100000 * 15 | getDigit d 1000000 16 | -------------------------------------------------------------------------------- /src/040. Champernowne's constant/040.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | public static void main(String[] args) { 3 | StringBuilder sb = new StringBuilder(); 4 | 5 | int n = 1; 6 | sb.append('0'); //so that index starts from 1 7 | while (sb.length() <= 1000000) { 8 | sb.append(Integer.toString(n)); 9 | n++; 10 | } 11 | String str = sb.toString(); 12 | 13 | int d1 = str.charAt(1) - '0'; 14 | int d10 = str.charAt(10) - '0'; 15 | int d100 = str.charAt(100) - '0'; 16 | int d1000 = str.charAt(1000) - '0'; 17 | int d10000 = str.charAt(10000) - '0'; 18 | int d100000 = str.charAt(100000) - '0'; 19 | int d1000000 = str.charAt(1000000) - '0'; 20 | System.out.println(d1 * d10 * d100 * d1000 * d10000 * d100000 * d1000000); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/040. Champernowne's constant/040.lua: -------------------------------------------------------------------------------- 1 | local t = {} 2 | for i = 1, 200000 do 3 | t[i] = tostring(i) 4 | end 5 | local numStr = table.concat(t) 6 | local d1 = tonumber(string.sub(numStr, 1, 1)) 7 | local d10 = tonumber(string.sub(numStr, 10, 10)) 8 | local d100 = tonumber(string.sub(numStr, 100, 100)) 9 | local d1000 = tonumber(string.sub(numStr, 1000, 1000)) 10 | local d10000 = tonumber(string.sub(numStr, 10000, 10000)) 11 | local d100000 = tonumber(string.sub(numStr, 100000, 100000)) 12 | local d1000000 = tonumber(string.sub(numStr, 1000000, 1000000)) 13 | 14 | print(d1 * d10 * d100 * d1000 * d10000 * d100000 * d1000000) -------------------------------------------------------------------------------- /src/040. Champernowne's constant/040.py: -------------------------------------------------------------------------------- 1 | s = "" 2 | n = 0 3 | while len(s) <= 1000000: 4 | s += str(n) 5 | n += 1 6 | prod = 1 7 | for i in range(0, 7): 8 | prod *= int(s[10 ** i]) 9 | print(prod) 10 | -------------------------------------------------------------------------------- /src/040. Champernowne's constant/040.rb: -------------------------------------------------------------------------------- 1 | d = (0 .. 200_000).to_a.join 2 | puts [d[1], d[10], d[100], d[1_000], d[10_000], d[100_000], d[1000_000]].map(&:to_i).inject(:*) 3 | -------------------------------------------------------------------------------- /src/041. Pandigital prime/041.rb: -------------------------------------------------------------------------------- 1 | require 'prime' 2 | pandigital = [] 3 | 9.downto(1) do |digit| 4 | (1 .. digit).to_a.permutation(digit).each do |arr| 5 | num = 0 6 | arr.each do |d| 7 | num = num * 10 + d 8 | end 9 | pandigital << num if Prime.prime? num 10 | end 11 | end 12 | 13 | puts pandigital.max -------------------------------------------------------------------------------- /src/042. Coded triangle numbers/042.rb: -------------------------------------------------------------------------------- 1 | $triangles = [0] 2 | 3 | def expand_triangles(max) 4 | while $triangles.last < max 5 | n = $triangles.size 6 | $triangles << n * (n + 1) / 2 7 | end 8 | end 9 | 10 | def check_triangle(num) 11 | if $triangles.last < num 12 | expand_triangles(num) 13 | end 14 | $triangles.include? num 15 | end 16 | 17 | def word_value(word) 18 | word.chars.map {|c| c.ord - 'A'.ord + 1}.inject(:+) 19 | end 20 | 21 | count = 0 22 | words = IO.read('p042_words.txt').split(',') 23 | words.map do |word| 24 | word = word.delete('"') 25 | value = word_value(word) 26 | if (check_triangle(value)) 27 | count += 1 28 | end 29 | end 30 | puts count 31 | -------------------------------------------------------------------------------- /src/043. Sub-string divisibility/043.py: -------------------------------------------------------------------------------- 1 | from itertools import permutations 2 | 3 | def num3(arr, index): 4 | return arr[index - 1] * 100 + arr[index] * 10 + arr[index + 1] 5 | 6 | pandigital = [] 7 | for arr in permutations(range(0, 10)): 8 | if arr[0] != 0 and num3(arr, 2) % 2 == 0 and num3(arr, 3) % 3 == 0 and num3(arr, 4) % 5 == 0 and num3(arr, 5) % 7 == 0 and num3(arr, 6) % 11 == 0 and num3(arr, 7) % 13 == 0 and num3(arr, 8) % 17 == 0: 9 | num = 0 10 | num = int(''.join([str(d) for d in arr])) 11 | pandigital.append(num) 12 | 13 | print(sum(pandigital)) 14 | -------------------------------------------------------------------------------- /src/043. Sub-string divisibility/043.rb: -------------------------------------------------------------------------------- 1 | def num3(arr, index) 2 | arr[index - 1] * 100 + arr[index] * 10 + arr[index + 1] 3 | end 4 | 5 | pandigital = [] 6 | (0 .. 9).to_a.permutation(10).each do |arr| 7 | if arr[0] != 0 and num3(arr, 2) % 2 == 0 and num3(arr, 3) % 3 == 0 and num3(arr, 4) % 5 == 0 and num3(arr, 5) % 7 == 0 and num3(arr, 6) % 11 == 0 and num3(arr, 7) % 13 == 0 and num3(arr, 8) % 17 == 0 8 | num = 0 9 | arr.each {|d| num = num * 10 + d} 10 | pandigital << num 11 | end 12 | end 13 | 14 | puts pandigital.inject(:+) -------------------------------------------------------------------------------- /src/044. Pentagon numbers/044.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() { 5 | long long upper_limit = 10000LL; 6 | std::set pentagons; 7 | for (long long i = 1; i <= upper_limit; i++) { 8 | pentagons.insert(i * (3 * i - 1) / 2); 9 | } 10 | for (long long m : pentagons) { 11 | for (long long n : pentagons) { 12 | auto found1 = pentagons.find(m + n); 13 | if (found1 != pentagons.end()) { 14 | auto found2 = pentagons.find(m + n + n); 15 | if (found2 != pentagons.end()) { 16 | std::cout << m << std::endl; 17 | return 0; 18 | } 19 | } 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/044. Pentagon numbers/044.java: -------------------------------------------------------------------------------- 1 | import java.util.TreeSet; 2 | 3 | public class Main { 4 | 5 | public static void main(String[] args) { 6 | 7 | long upperLimit = 10_000; 8 | TreeSet pentagons = new TreeSet<>(); 9 | for (long i = 1; i <= upperLimit; i++) { 10 | pentagons.add(i * (3 * i - 1) / 2); 11 | } 12 | for (long m : pentagons) { 13 | for (long n : pentagons) { 14 | if (pentagons.contains(m + n)) { 15 | if (pentagons.contains(m + n + n)) { 16 | System.out.println(m); 17 | return; 18 | } 19 | } 20 | } 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/045. Triangular, pentagonal, and hexagonal/045.java: -------------------------------------------------------------------------------- 1 | import java.util.HashSet; 2 | import java.util.Set; 3 | import java.util.TreeSet; 4 | 5 | public class Main { 6 | public static void main(String[] args) { 7 | Set triangle = new HashSet<>(); 8 | Set pentagonal = new HashSet<>(); 9 | Set hexagonal = new HashSet<>(); 10 | for (long n = 1; n < 100000; n++) { 11 | triangle.add(n * (n + 1) / 2); 12 | pentagonal.add(n * (3 * n - 1) / 2); 13 | hexagonal.add(n * (2 * n - 1)); 14 | } 15 | 16 | TreeSet result = new TreeSet<>(); 17 | for (long num: triangle) { 18 | if (pentagonal.contains(num) && hexagonal.contains(num)) { 19 | result.add(num); 20 | } 21 | } 22 | 23 | System.out.println(result.higher((long)40755)); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/045. Triangular, pentagonal, and hexagonal/045.lua: -------------------------------------------------------------------------------- 1 | local triangle, pentagonal, hexagonal = {}, {}, {} 2 | for n = 1, 100000 do 3 | triangle[n * (n + 1) / 2] = true 4 | pentagonal[n * (3 * n - 1) / 2] = true 5 | hexagonal[n * (2 * n - 1)] = true 6 | end 7 | 8 | local result = {} 9 | for v in pairs(triangle) do 10 | if pentagonal[v] and hexagonal[v] then 11 | table.insert(result, v) 12 | end 13 | end 14 | 15 | table.sort(result) 16 | for _, r in ipairs(result) do 17 | if r > 40755 then 18 | print(r) 19 | break 20 | end 21 | end 22 | -------------------------------------------------------------------------------- /src/045. Triangular, pentagonal, and hexagonal/045.rb: -------------------------------------------------------------------------------- 1 | triangle, pentagonal, hexagonal = [], [], [] 2 | 1.upto(100000) do |n| 3 | triangle << n * (n + 1) / 2 4 | pentagonal << n * (3 * n - 1) / 2 5 | hexagonal << n * (2 * n - 1) 6 | end 7 | 8 | puts (triangle & pentagonal & hexagonal).keep_if {|num| num > 40755}.min 9 | -------------------------------------------------------------------------------- /src/046. Goldbach's other conjecture/046.rb: -------------------------------------------------------------------------------- 1 | require 'prime' 2 | require 'set' 3 | 4 | upper_limit = 10 ** 6 5 | 6 | primes = [] 7 | Prime.each(upper_limit) {|p| primes << p} 8 | 9 | squares = [] 10 | n = 0 # include 0 to cross out primes 11 | while n * n < upper_limit / 2 12 | squares << n * n * 2 13 | n += 1 14 | end 15 | 16 | sieve = Set.new 17 | primes.each do |p| 18 | squares.each do |s| 19 | break if p + s > upper_limit 20 | sieve.add(p + s) 21 | end 22 | end 23 | 24 | 9.step(upper_limit, 2) do |n| 25 | if not sieve.include? n 26 | puts n 27 | break 28 | end 29 | end 30 | -------------------------------------------------------------------------------- /src/047. Distinct primes factors/047.rb: -------------------------------------------------------------------------------- 1 | require 'prime' 2 | 3 | n = 1 4 | consecutive = 0 5 | while true 6 | if n.prime_division.size == 4 7 | consecutive += 1 8 | else 9 | consecutive = 0 10 | end 11 | if consecutive == 4 12 | puts n - 3 13 | break 14 | end 15 | n += 1 16 | end 17 | -------------------------------------------------------------------------------- /src/048. Self powers/048.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "math/big" 6 | ) 7 | 8 | func main() { 9 | var m big.Int 10 | m.Exp(big.NewInt(10), big.NewInt(10), nil) 11 | 12 | var sum10digit big.Int 13 | for i := int64(1); i <= int64(1000); i++ { 14 | var power big.Int 15 | power.Exp(big.NewInt(i), big.NewInt(i), &m) 16 | sum10digit.Add(&sum10digit, &power) 17 | sum10digit.Mod(&sum10digit, &m) 18 | } 19 | fmt.Println(sum10digit.String()) 20 | } -------------------------------------------------------------------------------- /src/048. Self powers/048.hs: -------------------------------------------------------------------------------- 1 | main = print $ (sum $ map (\n -> n^n) [1 .. 1000]) `mod` 10^10 2 | -------------------------------------------------------------------------------- /src/048. Self powers/048.java: -------------------------------------------------------------------------------- 1 | import java.math.BigInteger; 2 | 3 | public class Main { 4 | public static void main(String[] args) { 5 | final BigInteger tenTo10 = BigInteger.TEN.pow(10); 6 | BigInteger result = BigInteger.ZERO; 7 | for (int i = 1; i <= 1000; i++) { 8 | result = result.add(BigInteger.valueOf(i).pow(i)); 9 | result = result.mod(tenTo10); 10 | } 11 | System.out.println(result); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/048. Self powers/048.py: -------------------------------------------------------------------------------- 1 | n = 0 2 | 3 | for i in range(1, 1001): 4 | n += i ** i 5 | n %= 10 ** 10 6 | 7 | print(n) 8 | -------------------------------------------------------------------------------- /src/048. Self powers/048.rb: -------------------------------------------------------------------------------- 1 | sum10digit = 0 2 | 1.upto(1000) do |n| 3 | sum10digit += n ** n 4 | sum10digit %= 10 ** 10 5 | end 6 | 7 | puts(sum10digit) -------------------------------------------------------------------------------- /src/049. Prime permutations/049.rb: -------------------------------------------------------------------------------- 1 | require 'prime' 2 | 3 | class Integer 4 | def to_sorted 5 | self.to_s.chars.sort.join 6 | end 7 | end 8 | 9 | primes = Prime.each(10000).to_a.keep_if {|p| p > 1000} 10 | counter = Hash.new {|hash, key| hash[key] = []} 11 | primes.each { |p| counter[p.to_sorted] << p } 12 | candidates = counter.keep_if {|k, v| v.size >= 3 }.values 13 | 14 | result = [] 15 | candidates.each do |a| 16 | a.combination(3) do |b| 17 | if b[1] - b[0] == b[2] - b[1] 18 | result << b 19 | end 20 | end 21 | end 22 | 23 | puts result.keep_if { |a| a[0] != 1487}[0].map(&:to_s).join 24 | -------------------------------------------------------------------------------- /src/050. Consecutive prime sum/050.rb: -------------------------------------------------------------------------------- 1 | require 'prime' 2 | 3 | sum = 0 4 | max = 0 5 | Prime.each do |prime| 6 | sum += prime 7 | result = sum 8 | Prime.each(prime) do |small| 9 | if Prime.prime? result 10 | max = result if result > max and result < 1000000 11 | break 12 | end 13 | result -= small 14 | end 15 | break if result > 1000000 16 | end 17 | 18 | puts max -------------------------------------------------------------------------------- /src/051. Prime digit replacements/051.rb: -------------------------------------------------------------------------------- 1 | require 'prime' 2 | require 'set' 3 | 4 | def mask_adjacent_digits(n) 5 | masked_nums = Set.new 6 | digit_index = Hash.new {|h, k| h[k] = []} 7 | n_chars = n.to_s.chars 8 | n_chars.each_index do |i| 9 | break if i == n_chars.size - 1 # ignore the last digit 10 | d = n_chars[i] 11 | digit_index[d] << i 12 | end 13 | digit_index.each do |d, a| 14 | if a.size >= 2 15 | 2.upto(a.size) do |c_num| 16 | a.combination(c_num) do |indexes| 17 | masked = Array.new(n_chars) 18 | 0.upto(c_num - 1) do |i| 19 | masked[indexes[i]] = '*' 20 | end 21 | masked_nums << masked.join 22 | end 23 | end 24 | end 25 | end 26 | masked_nums 27 | end 28 | 29 | candidates = Hash.new {|h, k| h[k] = []} 30 | 31 | Prime.each do |p| 32 | masked = mask_adjacent_digits(p) 33 | if not masked.empty? 34 | masked.each do |m| 35 | candidates[m] << p 36 | if candidates[m].size >= 8 37 | puts candidates[m].min 38 | exit 39 | end 40 | end 41 | end 42 | end 43 | -------------------------------------------------------------------------------- /src/052. Permuted multiples/052.hs: -------------------------------------------------------------------------------- 1 | import Data.List 2 | import Data.Maybe 3 | 4 | main = print $ fromJust $ find permutedMultiples [1..] 5 | 6 | permutedMultiples :: Integer -> Bool 7 | permutedMultiples n = toSorted n == toSorted (n * 2) 8 | && toSorted n == toSorted (n * 3) 9 | && toSorted n == toSorted (n * 4) 10 | && toSorted n == toSorted (n * 5) 11 | && toSorted n == toSorted (n * 6) 12 | 13 | toSorted :: Integer -> String 14 | toSorted n = sort $ show n 15 | -------------------------------------------------------------------------------- /src/052. Permuted multiples/052.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | public class Main { 4 | 5 | public static void main(String[] args) { 6 | long n = 1; 7 | while (true) { 8 | String sorted = toSorted(n); 9 | if (sorted.equals(toSorted(n * 2)) 10 | && sorted.equals(toSorted(n * 3)) 11 | && sorted.equals(toSorted(n * 4)) 12 | && sorted.equals(toSorted(n * 5)) 13 | && sorted.equals(toSorted(n * 6))) { 14 | System.out.println(n); 15 | break; 16 | } 17 | n++; 18 | } 19 | } 20 | 21 | private static String toSorted(long n) { 22 | return sortString(Long.toString(n)); 23 | } 24 | 25 | private static String sortString(String original) { 26 | char[] chars = original.toCharArray(); 27 | Arrays.sort(chars); 28 | return new String(chars); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/052. Permuted multiples/052.lua: -------------------------------------------------------------------------------- 1 | function to_sorted(n) 2 | local sorted = {} 3 | for d in tostring(n):gmatch("%d") do 4 | table.insert(sorted, d) 5 | end 6 | table.sort(sorted) 7 | return table.concat(sorted) 8 | end 9 | 10 | local n = 1 11 | while true do 12 | if to_sorted(n) == to_sorted(n * 2) 13 | and to_sorted(n) == to_sorted(n * 3) 14 | and to_sorted(n) == to_sorted(n * 4) 15 | and to_sorted(n) == to_sorted(n * 5) 16 | and to_sorted(n) == to_sorted(n * 6) then 17 | print(n) 18 | break 19 | end 20 | n = n + 1 21 | end 22 | -------------------------------------------------------------------------------- /src/052. Permuted multiples/052.py: -------------------------------------------------------------------------------- 1 | def to_sorted_str(num): 2 | return ''.join(sorted(str(num))) 3 | 4 | n = 1 5 | while True: 6 | sorted_str = to_sorted_str(n) 7 | if to_sorted_str(n * 2) == sorted_str and\ 8 | to_sorted_str(n * 3) == sorted_str and\ 9 | to_sorted_str(n * 4) == sorted_str and\ 10 | to_sorted_str(n * 5) == sorted_str and\ 11 | to_sorted_str(n * 6) == sorted_str: 12 | print(n) 13 | break 14 | n += 1 15 | -------------------------------------------------------------------------------- /src/052. Permuted multiples/052.rb: -------------------------------------------------------------------------------- 1 | class Integer 2 | def to_sorted 3 | self.to_s.chars.sort.join 4 | end 5 | end 6 | 7 | n = 1 8 | while true 9 | sorted = n.to_sorted 10 | if (n * 2).to_sorted == sorted and 11 | (n * 3).to_sorted == sorted and 12 | (n * 4).to_sorted == sorted and 13 | (n * 5).to_sorted == sorted and 14 | (n * 6).to_sorted == sorted 15 | puts n 16 | break 17 | end 18 | n += 1 19 | end 20 | -------------------------------------------------------------------------------- /src/053. Combinatoric selections/053.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "math/big" 6 | ) 7 | 8 | func main() { 9 | const upperLimit = 100 10 | factorials := make([]*big.Int, upperLimit + 1) 11 | factorials[0] = big.NewInt(1) 12 | for i := 1; i <= upperLimit; i++ { 13 | var f big.Int 14 | f.Mul(factorials[i - 1], big.NewInt(int64(i))) 15 | factorials[i] = &f 16 | } 17 | 18 | count := 0 19 | for n := 1; n <= upperLimit; n++ { 20 | for r := 1; r <= n; r++ { 21 | var c big.Int 22 | c.Set(factorials[n]) 23 | c.Div(&c, factorials[r]) 24 | c.Div(&c, factorials[n - r]) 25 | if c.Cmp(big.NewInt(1000000)) > 0 { 26 | count++ 27 | } 28 | } 29 | } 30 | fmt.Println(count) 31 | } -------------------------------------------------------------------------------- /src/053. Combinatoric selections/053.java: -------------------------------------------------------------------------------- 1 | import java.math.BigInteger; 2 | import java.util.ArrayList; 3 | 4 | public class Main { 5 | public static void main(String[] args) { 6 | final int UPPER_LIMIT = 100; 7 | ArrayList factorials = new ArrayList<>(); 8 | factorials.add(BigInteger.ONE); 9 | for (int i = 1; i <= UPPER_LIMIT; i++) { 10 | factorials.add(factorials.get(i - 1).multiply(BigInteger.valueOf(i))); 11 | } 12 | 13 | int count = 0; 14 | for (int n = 1; n <= UPPER_LIMIT; n++) { 15 | for (int r = 1; r <= n; r++) { 16 | if (factorials.get(n).divide(factorials.get(r)).divide(factorials.get(n - r)) 17 | .compareTo(BigInteger.valueOf(1_000_000)) > 0) { 18 | count += 1; 19 | } 20 | } 21 | } 22 | 23 | System.out.println(count); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/053. Combinatoric selections/053.py: -------------------------------------------------------------------------------- 1 | factorials = [1] 2 | for n in range(1, 101): 3 | factorials.append(factorials[n - 1] * n) 4 | 5 | count = 0 6 | for n in range(1, 101): 7 | for r in range(1, n + 1): 8 | if factorials[n] / factorials[r] / factorials[n - r] > 1000000: 9 | count += 1 10 | 11 | print(count) 12 | -------------------------------------------------------------------------------- /src/053. Combinatoric selections/053.rb: -------------------------------------------------------------------------------- 1 | factorials = [1] 2 | 1.upto(100) do |n| 3 | factorials[n] = factorials[n - 1] * n 4 | end 5 | 6 | count = 0 7 | 1.upto(100) do |n| 8 | 1.upto(n) do |r| 9 | count += 1 if factorials[n] / factorials[r] / factorials[n - r] > 1_000_000 10 | end 11 | end 12 | 13 | puts count 14 | -------------------------------------------------------------------------------- /src/055. Lychrel numbers/055.py: -------------------------------------------------------------------------------- 1 | def is_lychrel(num): 2 | i = 0 3 | while i < 50: 4 | num = num + int(str(num)[::-1]) 5 | if num == int(str(num)[::-1]): 6 | return False 7 | i += 1 8 | return True 9 | 10 | counter = 0 11 | for i in range(1, 10001): 12 | if is_lychrel(i): 13 | counter += 1 14 | 15 | print(counter) 16 | -------------------------------------------------------------------------------- /src/055. Lychrel numbers/055.rb: -------------------------------------------------------------------------------- 1 | class Integer 2 | def is_lychrel? 3 | num = self 4 | i = 0 5 | while i < 50 6 | num = num + num.to_s.reverse.to_i 7 | if num == num.to_s.reverse.to_i 8 | return false 9 | end 10 | i += 1 11 | end 12 | true 13 | end 14 | end 15 | 16 | counter = 0 17 | 1.upto(10000) do |num| 18 | if num.is_lychrel? 19 | counter += 1 20 | end 21 | end 22 | puts counter 23 | -------------------------------------------------------------------------------- /src/056. Powerful digit sum/056.hs: -------------------------------------------------------------------------------- 1 | import Data.Char 2 | 3 | main = print $ maximum [sum $ map digitToInt . show $ a ^ b | a <- [1 .. 99], b <- [1 .. 99]] 4 | -------------------------------------------------------------------------------- /src/056. Powerful digit sum/056.java: -------------------------------------------------------------------------------- 1 | import java.math.BigInteger; 2 | 3 | public class Main { 4 | 5 | public static void main(String[] args) { 6 | long max = 0; 7 | for (int a = 1; a < 100; a++) { 8 | for (int b = 1; b < 100; b++) { 9 | BigInteger exp = BigInteger.valueOf(a).pow(b); 10 | long expDigitSum = digitSum(exp); 11 | if (expDigitSum > max) { 12 | max = expDigitSum; 13 | } 14 | } 15 | } 16 | System.out.println(max); 17 | } 18 | 19 | private static long digitSum(BigInteger n){ 20 | long sum = 0; 21 | while (n.compareTo(BigInteger.ZERO) > 0) { 22 | BigInteger[] quotientAndRemainder = n.divideAndRemainder(BigInteger.valueOf(10)); 23 | sum += quotientAndRemainder[1].longValue(); 24 | n = quotientAndRemainder[0]; 25 | } 26 | return sum; 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/056. Powerful digit sum/056.py: -------------------------------------------------------------------------------- 1 | def digit_sum(n): 2 | digits = 0 3 | while n > 0: 4 | digits += n % 10 5 | n //= 10 6 | return digits 7 | 8 | max = 0 9 | for a in range(1, 100): 10 | for b in range(1, 100): 11 | exp = a ** b 12 | if digit_sum(exp) > max: 13 | max = digit_sum(exp) 14 | 15 | print(max) 16 | 17 | -------------------------------------------------------------------------------- /src/056. Powerful digit sum/056.rb: -------------------------------------------------------------------------------- 1 | class Integer 2 | def digit_sum 3 | n = self 4 | digits = 0 5 | while n > 0 6 | digits += n % 10 7 | n /= 10 8 | end 9 | return digits 10 | end 11 | end 12 | 13 | max = 0 14 | 1.upto(99) do |a| 15 | 1.upto(99) do |b| 16 | exp = a ** b 17 | if exp.digit_sum > max 18 | max = exp.digit_sum 19 | end 20 | end 21 | end 22 | 23 | puts max 24 | -------------------------------------------------------------------------------- /src/057. Square root convergents/057.py: -------------------------------------------------------------------------------- 1 | from fractions import Fraction 2 | 3 | fraction = Fraction(3, 2) 4 | count = 0 5 | for i in range(1000): 6 | if len(str(fraction.numerator)) > len(str(fraction.denominator)): 7 | count += 1 8 | fraction = 1 / (1 + fraction) + 1 9 | 10 | print(count) 11 | -------------------------------------------------------------------------------- /src/057. Square root convergents/057.rb: -------------------------------------------------------------------------------- 1 | fraction = Rational(3, 2) 2 | count = 0 3 | 4 | 1000.times do 5 | if fraction.numerator.to_s.length > fraction.denominator.to_s.length 6 | count += 1 7 | end 8 | fraction = 1 / (1 + fraction) + 1 9 | end 10 | 11 | puts count 12 | -------------------------------------------------------------------------------- /src/058. Spiral primes/058.rb: -------------------------------------------------------------------------------- 1 | require 'prime' 2 | 3 | n = 1 4 | total_count = 1 5 | prime_count = 0 6 | while true 7 | n += 2 8 | total_count += 4 9 | prime_count += 1 if (n * n - n + 1).prime? 10 | prime_count += 1 if (n * n - 2 * n + 2).prime? 11 | prime_count += 1 if (n * n - 3 * n + 3).prime? 12 | if prime_count.fdiv(total_count) <= 0.1 13 | puts n 14 | break 15 | end 16 | end 17 | -------------------------------------------------------------------------------- /src/059. XOR decryption/059.lua: -------------------------------------------------------------------------------- 1 | local encrypted_codes = {} 2 | local cipher_file = io.open("p059_cipher.txt", "r") 3 | for c in cipher_file:read("*a"):gmatch("%d+") do 4 | table.insert(encrypted_codes, c) 5 | end 6 | 7 | -- https://en.wikipedia.org/wiki/Dolch_word_list 8 | local common_english_words = {} 9 | local common_words_file = io.open("common_english_words.txt", "r") 10 | for line in common_words_file:lines() do 11 | for word in line:gmatch("%w+") do 12 | table.insert(common_english_words, word) 13 | end 14 | end 15 | 16 | function decrypt(encrypted_codes, key) 17 | local decrypted_words = {} 18 | local i = 1 19 | for _, m in ipairs(encrypted_codes) do 20 | table.insert(decrypted_words, string.char(m ~ key[i])) 21 | i = i + 1 22 | if i > 3 then 23 | i = 1 24 | end 25 | end 26 | return table.concat(decrypted_words) 27 | end 28 | 29 | 30 | local max_matches = 0 31 | local max_match_key = 'no_match' 32 | local a_ascii, z_ascii = string.byte("a"), string.byte("z") 33 | for a = a_ascii, z_ascii do 34 | for b = a_ascii, z_ascii do 35 | for c = a_ascii, z_ascii do 36 | local key = {a, b, c} 37 | local decrypted_words = decrypt(encrypted_codes, key) 38 | local match_count = 0 39 | for _, word in ipairs(common_english_words) do 40 | for m in decrypted_words:gmatch("%W" .. word .. "%W") do 41 | match_count = match_count + 1 42 | end 43 | end 44 | if match_count > max_matches then 45 | max_matches = match_count 46 | max_match_key = key 47 | end 48 | end 49 | end 50 | end 51 | local max_decrypted_words = decrypt(encrypted_codes, max_match_key) 52 | local ascii_sum = 0 53 | for i = 1, #max_decrypted_words do 54 | ascii_sum = ascii_sum + max_decrypted_words:byte(i) 55 | end 56 | print(ascii_sum) 57 | -------------------------------------------------------------------------------- /src/059. XOR decryption/059.rb: -------------------------------------------------------------------------------- 1 | encrypted_codes = [] 2 | File.read('p059_cipher.txt').split(',').each do |c| 3 | encrypted_codes << c.to_i 4 | end 5 | 6 | # https://en.wikipedia.org/wiki/Dolch_word_list 7 | common_english_words = [] 8 | File.read('common_english_words.txt').lines do |line| 9 | line.split(',').each do |word| 10 | word = word.strip 11 | common_english_words << word unless word.empty? 12 | end 13 | end 14 | 15 | def decrypt(encrypted_codes, key) 16 | decrypted_words = '' 17 | encrypted_codes.each_slice(3) do |m| 18 | decrypted_words << (m[0] ^ key[0].ord) 19 | decrypted_words << (m[1] ^ key[1].ord) 20 | decrypted_words << (m[2] ^ key[2].ord) 21 | end 22 | decrypted_words 23 | end 24 | 25 | max_matches = 0 26 | max_match_key = 'no_match' 27 | 'aaa'.upto('zzz') do |key| 28 | decrypted_words = decrypt(encrypted_codes, key) 29 | match_count = 0 30 | common_english_words.each do |word| 31 | r = Regexp.new('\W' + word + '\W') 32 | m = decrypted_words.match r 33 | if m != nil 34 | match_count += m.size 35 | end 36 | end 37 | if match_count > max_matches 38 | max_matches = match_count 39 | max_match_key = key 40 | end 41 | end 42 | puts decrypt(encrypted_codes, max_match_key).chars.map(&:ord).inject(:+) 43 | -------------------------------------------------------------------------------- /src/059. XOR decryption/common_english_words.txt: -------------------------------------------------------------------------------- 1 | a, and, away, big, blue, can, come, down, find, for, funny, go, help, here, I, in, is, it, jump, little, look, make, me, my, not, one, play, red, run, said, see, the, three, to, two, up, we, where, yellow, you 2 | 3 | all, am, are, at, ate, be, black, brown, but, came, did, do, eat, four, get, good, have, he, into, like, must, new, no, now, on, our, out, please, pretty, ran, ride, saw, say, she, so, soon, that, there, they, this, too, under, want, was, well, went, what, white, who, will, with, yes 4 | 5 | after, again, an, any, as, ask, by, could, every, fly, from, give, giving, had, has, her, him, his, how, just, know, let, live, may, of, old, once, open, over, put, round, some, stop, take, thank, them, then, think, walk, were, when 6 | 7 | always, around, because, been, before, best, both, buy, call, cold, does, don't, fast, first, five, found, gave, goes, green, its, made, many, off, or, pull, read, right, sing, sit, sleep, tell, their, these, those, upon, us, use, very, wash, which, why, wish, work, would, write, your 8 | 9 | about, better, bring, carry, clean, cut, done, draw, drink, eight, fall, far, full, got, grow, hold, hot, hurt, if, keep, kind, laugh, light, long, much, myself, never, nine, only, own, pick, seven, shall, show, six, small, start, ten, today, together, try, warm 10 | 11 | apple, baby, back, ball, bear, bed, bell, bird, birthday, boat, box, boy, bread, brother, cake, car, cat, chair, chicken, children, Christmas, coat, corn, cow, day, dog, doll, door, duck, egg, eye, farm, farmer, father, feet, fire, fish, floor, flower, game, garden, girl, good-bye, grass, ground, hand, head, hill, home, horse, house, kitty, leg, letter, man, men, milk, money, morning, mother, name, nest, night, paper, party, picture, pig, rabbit, rain, ring, robin, Santa Claus, school, seed, sheep, shoe, sister, snow, song, squirrel, stick, street, sun, table, thing, time, top, toy, tree, watch, water, way, wind, window, wood -------------------------------------------------------------------------------- /src/062. Cubic permutations/062.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | import java.util.Collections; 3 | import java.util.HashMap; 4 | import java.util.HashSet; 5 | import java.util.Map; 6 | import java.util.Set; 7 | 8 | public class Main { 9 | 10 | public static void main(String[] args) { 11 | Map> counter = new HashMap(); 12 | long n = 1; 13 | while (true) { 14 | long cube = n * n * n; 15 | String sorted = toSorted(cube); 16 | Set counted = counter.getOrDefault(sorted, new HashSet<>()); 17 | counted.add(cube); 18 | if (counted.size() == 5) { 19 | System.out.println(Collections.min(counted)); 20 | break; 21 | } 22 | counter.put(sorted, counted); 23 | n++; 24 | } 25 | } 26 | 27 | private static String toSorted(long n) { 28 | String s = Long.toString(n); 29 | char[] chars = s.toCharArray(); 30 | Arrays.sort(chars); 31 | return new String(chars); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/062. Cubic permutations/062.rb: -------------------------------------------------------------------------------- 1 | class Integer 2 | def to_sorted 3 | self.to_s.chars.sort.join 4 | end 5 | end 6 | 7 | counter = Hash.new {|hash, key| hash[key] = []} 8 | n = 1 9 | result = while true 10 | cube = n ** 3 11 | sorted = cube.to_sorted 12 | arr = counter[sorted] 13 | arr << cube 14 | break arr if arr.size == 5 15 | n += 1 16 | end 17 | 18 | puts arr.min -------------------------------------------------------------------------------- /src/063. Powerful digit counts/063.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() { 5 | int count = 0; 6 | for (int n = 1; ; ++n) { 7 | int start = (int)ceil(pow(pow(10, n - 1), (1.0 / (double)n))); 8 | count += 9 - start + 1; 9 | if (start > 9) { 10 | break; 11 | } 12 | } 13 | printf("%d\n", count); 14 | } 15 | -------------------------------------------------------------------------------- /src/063. Powerful digit counts/063.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() { 5 | int count = 0; 6 | for (int n = 1; ; ++n) { 7 | int start = static_cast(std::ceil(std::pow(std::pow(10, n - 1), (1.0 / static_cast(n))))); 8 | count += 9 - start + 1; 9 | if (start > 9) { 10 | break; 11 | } 12 | } 13 | std::cout << count << std::endl; 14 | } 15 | -------------------------------------------------------------------------------- /src/063. Powerful digit counts/063.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "math" 6 | ) 7 | 8 | func main() { 9 | count := 0 10 | for n := 1; ; n++ { 11 | start := int(math.Ceil(math.Pow(math.Pow10(n - 1), (1.0 / float64(n))))) 12 | count += 9 - start + 1 13 | if start > 9 { 14 | break 15 | } 16 | } 17 | fmt.Println(count) 18 | } 19 | -------------------------------------------------------------------------------- /src/063. Powerful digit counts/063.lua: -------------------------------------------------------------------------------- 1 | local count = 0 2 | for n = 1, math.huge do 3 | start = math.ceil((10 ^ (n - 1)) ^ (1.0 / n)) 4 | count = count + 9 - start + 1 5 | if start > 9 then 6 | break 7 | end 8 | end 9 | print(count) 10 | -------------------------------------------------------------------------------- /src/063. Powerful digit counts/063.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | count = 0 4 | n = 1 5 | while True: 6 | start = math.ceil((10 ** (n - 1)) ** (1.0 / n)) 7 | count += 9 - start + 1 8 | n += 1 9 | if start > 9: 10 | break 11 | print(count) 12 | -------------------------------------------------------------------------------- /src/063. Powerful digit counts/063.rb: -------------------------------------------------------------------------------- 1 | count = 0 2 | n = 1 3 | loop do 4 | start = ((10 ** (n - 1)) ** (1.0 / n)).ceil 5 | count += 9 - start + 1 6 | n += 1 7 | break if start > 9 8 | end 9 | puts count 10 | -------------------------------------------------------------------------------- /src/064. Odd period square roots/064.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | def sqrt_fraction_period(n): 4 | sqrt = math.sqrt(n) 5 | if sqrt == int(sqrt): 6 | return 0 7 | # https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Algorithm 8 | m = [0] 9 | d = [1] 10 | a = [math.floor(sqrt)] 11 | period = 0 12 | while True: 13 | new_m = d[-1] * a[-1] - m[-1] 14 | new_d = (n - new_m * new_m) / d[-1] 15 | new_a = math.floor((sqrt + new_m) / new_d) 16 | if period > 1 and m[-1] == m[1] and d[-1] == d[1] and a[-1] == a[1] \ 17 | and new_m == m[2] and new_d == d[2] and new_a == a[2]: 18 | return period - 1 19 | m.append(new_m) 20 | d.append(new_d) 21 | a.append(new_a) 22 | period += 1 23 | 24 | count = 0 25 | for n in range(1, 10001): 26 | if sqrt_fraction_period(n) % 2 == 1: 27 | count += 1 28 | print(count) 29 | -------------------------------------------------------------------------------- /src/064. Odd period square roots/064.rb: -------------------------------------------------------------------------------- 1 | def sqrt_fraction_period(n) 2 | sqrt = Math.sqrt(n) 3 | return 0 if sqrt.to_i == sqrt 4 | # https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Algorithm 5 | m = [0] 6 | d = [1] 7 | a = [sqrt.floor] 8 | period = 0 9 | loop do 10 | new_m = d.last * a.last - m.last 11 | new_d = (n - new_m * new_m) / d.last 12 | new_a = ((sqrt + new_m) / new_d).floor 13 | if period > 1 and m.last == m[1] and d.last == d[1] and a.last == a[1] \ 14 | and new_m == m[2] and new_d == d[2] and new_a == a[2] 15 | return period - 1 16 | end 17 | m << new_m 18 | d << new_d 19 | a << new_a 20 | period += 1 21 | end 22 | end 23 | 24 | count = 0 25 | 1.upto(10_000) do |n| 26 | count += 1 if sqrt_fraction_period(n).odd? 27 | end 28 | puts count 29 | -------------------------------------------------------------------------------- /src/065. Convergents of e/065.py: -------------------------------------------------------------------------------- 1 | from fractions import Fraction 2 | 3 | # n starts from 2 4 | def fraction_seq(n): 5 | if n % 3 == 0: 6 | return n // 3 * 2 7 | else: 8 | return 1 9 | 10 | e = Fraction(0) 11 | for n in range(100, 1, -1): 12 | e = Fraction(1) / (fraction_seq(n) + e) 13 | 14 | e += 2 15 | print(sum(map(int, list(str(e.numerator))))) 16 | -------------------------------------------------------------------------------- /src/065. Convergents of e/065.rb: -------------------------------------------------------------------------------- 1 | # n starts from 2 2 | def fraction_seq(n) 3 | if n % 3 == 0 4 | n / 3 * 2 5 | else 6 | 1 7 | end 8 | end 9 | 10 | e = 0 11 | 100.downto(2) do |n| 12 | e = Rational('1') / (fraction_seq(n) + e) 13 | end 14 | e += 2 15 | puts e.numerator.to_s.chars.map(&:to_i).inject(:+) 16 | -------------------------------------------------------------------------------- /src/067. Maximum path sum II/067.py: -------------------------------------------------------------------------------- 1 | triangle = [] 2 | with open('p067_triangle.txt') as f: 3 | for line in f: 4 | triangle.append([int(n) for n in line.split()]) 5 | 6 | for row in range(1, len(triangle)): 7 | triangle[row - 1].append(0) 8 | for col in range(0, len(triangle[row])): 9 | triangle[row][col] += max(triangle[row - 1][col], triangle[row - 1][col - 1]) 10 | 11 | print(max(triangle[-1])) 12 | -------------------------------------------------------------------------------- /src/067. Maximum path sum II/067.rb: -------------------------------------------------------------------------------- 1 | file_content = IO.read('p067_triangle.txt') 2 | 3 | triangle = [] 4 | file_content.lines do |line| 5 | triangle << line.split.map(&:to_i) 6 | end 7 | 8 | 1.upto(triangle.size - 1) do |row| 9 | triangle[row - 1] << 0 10 | 0.upto(triangle[row].size - 1) do |col| 11 | triangle[row][col] += [triangle[row - 1][col], triangle[row - 1][col - 1]].max 12 | end 13 | end 14 | 15 | puts triangle.last.max -------------------------------------------------------------------------------- /src/069. Totient maximum/069.rb: -------------------------------------------------------------------------------- 1 | require 'prime' 2 | 3 | # return phi(n) / n 4 | def phi_norm(n) 5 | primes = n.prime_division.map(&:first) 6 | primes.map { |p| 1.0 - 1.0 / p }.inject(:*) 7 | end 8 | 9 | puts (2 .. 1_000_000).min_by {|n| phi_norm(n)} 10 | -------------------------------------------------------------------------------- /src/071. Ordered fractions/071.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "math/big" 6 | ) 7 | 8 | func main() { 9 | best := big.NewRat(0, 1) 10 | for d := int64(1); d <= int64(1000000); d++ { 11 | n := d * 3 / 7 12 | r := big.NewRat(n, d) 13 | if r.Cmp(big.NewRat(3, 7)) < 0 && r.Cmp(best) > 0 { 14 | best = r 15 | } 16 | } 17 | fmt.Println(best.Num()) 18 | } -------------------------------------------------------------------------------- /src/071. Ordered fractions/071.py: -------------------------------------------------------------------------------- 1 | from fractions import Fraction 2 | 3 | best = 0 4 | 5 | for d in range(1, 1000001): 6 | n = d * 3 // 7 7 | r = Fraction(n, d) 8 | if r < Fraction(3, 7) and r > best: 9 | best = r 10 | 11 | print(best.numerator) 12 | -------------------------------------------------------------------------------- /src/071. Ordered fractions/071.rb: -------------------------------------------------------------------------------- 1 | best = 0 2 | 3 | 1.upto(1_000_000) do |d| 4 | n = d * 3 / 7 5 | r = Rational(n, d) 6 | if r < Rational(3, 7) and r > best 7 | best = r 8 | end 9 | end 10 | 11 | puts best.numerator -------------------------------------------------------------------------------- /src/072. Counting fractions/072.rb: -------------------------------------------------------------------------------- 1 | require 'prime' 2 | 3 | class Integer 4 | # Euler's totient function 5 | # see https://en.wikipedia.org/wiki/Euler%27s_totient_function 6 | def phi() 7 | prime_factors = self.prime_division.map {|row| row[0]} 8 | phi_value = self 9 | prime_factors.each do |p| 10 | phi_value = phi_value * (p - 1) / p 11 | end 12 | phi_value 13 | end 14 | end 15 | 16 | puts (2..1_000_000).map(&:phi).inject(:+) 17 | -------------------------------------------------------------------------------- /src/073. Counting fractions in a range/073.py: -------------------------------------------------------------------------------- 1 | from fractions import Fraction 2 | 3 | fractions = set() 4 | for d in range(1, 12001): 5 | for n in range(d // 3 + 1, d / 2): 6 | fractions.add(Fraction(n, d)) 7 | 8 | print(len(fractions) - 1) # remove the number 1/2 9 | -------------------------------------------------------------------------------- /src/073. Counting fractions in a range/073.rb: -------------------------------------------------------------------------------- 1 | require 'set' 2 | 3 | fractions = Set.new 4 | 1.upto(12_000) do |d| 5 | (d / 3 + 1).upto(d / 2) do |n| 6 | fractions.add(n.quo(d)) 7 | end 8 | end 9 | 10 | puts fractions.size - 1 # remove the number 1/2 11 | -------------------------------------------------------------------------------- /src/074. Digit factorial chains/074.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | std::vector factorial; 6 | void init_factorial(); 7 | long long digit_fact(long long n); 8 | 9 | int main() { 10 | init_factorial(); 11 | int counter = 0; 12 | for (long long n = 1; n <= 1000000LL; ++n) { 13 | long long m = n; 14 | std::unordered_set sequence; 15 | do { 16 | sequence.insert(m); 17 | m = digit_fact(m); 18 | } while (sequence.find(m) == sequence.end()); 19 | if (sequence.size() == 60) { 20 | ++counter; 21 | } 22 | } 23 | std::cout << counter << std::endl; 24 | } 25 | 26 | void init_factorial() { 27 | factorial.push_back(1); 28 | for (long long d = 1; d <= 9; ++d) { 29 | factorial.push_back(factorial[d - 1] * d); 30 | } 31 | } 32 | 33 | long long digit_fact(long long n) { 34 | long long sum = 0; 35 | while (n > 0) { 36 | sum += factorial[n % 10]; 37 | n /= 10; 38 | } 39 | return sum; 40 | } 41 | -------------------------------------------------------------------------------- /src/074. Digit factorial chains/074.py: -------------------------------------------------------------------------------- 1 | factorial = [1] 2 | for d in range(1, 10): 3 | factorial.append(factorial[-1] * d) 4 | 5 | def digit_fact(n): 6 | return sum([factorial[int(d)] for d in str(n)]) 7 | 8 | counter = 0 9 | for n in range(10 ** 6): 10 | m = n 11 | sequence = set() 12 | while True: 13 | sequence.add(m) 14 | m = digit_fact(m) 15 | if m in sequence: 16 | break 17 | if len(sequence) == 60: 18 | counter += 1 19 | 20 | print(counter) 21 | -------------------------------------------------------------------------------- /src/074. Digit factorial chains/074.rb: -------------------------------------------------------------------------------- 1 | require 'set' 2 | 3 | $factorial = [1] 4 | 1.upto(9) { |d| $factorial[d] = $factorial[d - 1] * d} 5 | 6 | def digit_fact(n) 7 | n.to_s.chars.map { |d| $factorial[d.to_i] }.inject(:+) 8 | end 9 | 10 | counter = 0 11 | 1.upto(10 ** 6) do |n| 12 | m = n 13 | sequence = Set.new 14 | begin 15 | sequence.add(m) 16 | m = digit_fact(m) 17 | end until sequence.include?(m) 18 | if sequence.size == 60 19 | counter += 1 20 | end 21 | end 22 | 23 | puts counter 24 | -------------------------------------------------------------------------------- /src/076. Counting summations/076.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | amount := 100 7 | coins := make([]int, amount - 1) 8 | for i := 0; i < len(coins); i++ { 9 | coins[i] = i + 1 10 | } 11 | ways := make([]int, amount + 1) 12 | ways[0] = 1 13 | for _, coin := range coins { 14 | for n := coin; n <= amount; n++ { 15 | ways[n] += ways[n - coin] 16 | } 17 | } 18 | fmt.Println(ways[amount]) 19 | } 20 | -------------------------------------------------------------------------------- /src/076. Counting summations/076.lua: -------------------------------------------------------------------------------- 1 | local amount = 100 2 | local coins = {} 3 | for i = 1, amount - 1 do 4 | coins[i] = i 5 | end 6 | local amount = 100 7 | local ways = {} 8 | for i = 0, amount + 1 do 9 | ways[i] = 0 10 | end 11 | ways[0] = 1 12 | for _, coin in ipairs(coins) do 13 | for n = coin, amount + 1 do 14 | ways[n] = ways[n] + ways[n - coin] 15 | end 16 | end 17 | 18 | print(ways[amount]) 19 | -------------------------------------------------------------------------------- /src/076. Counting summations/076.py: -------------------------------------------------------------------------------- 1 | amount = 100 2 | coins = list(range(1, amount)) 3 | ways = [0] * (amount + 1) 4 | ways[0] = 1 5 | for coin in coins: 6 | for n in range(coin, amount + 1): 7 | ways[n] += ways[n - coin] 8 | 9 | print(ways[amount]) 10 | -------------------------------------------------------------------------------- /src/076. Counting summations/076.rb: -------------------------------------------------------------------------------- 1 | amount = 100 2 | coins = (1 .. (amount - 1)).to_a 3 | ways = [0] * (amount + 1) 4 | ways[0] = 1 5 | coins.each do |coin| 6 | coin.upto(amount) do |n| 7 | ways[n] += ways[n - coin] 8 | end 9 | end 10 | 11 | puts ways[amount] 12 | -------------------------------------------------------------------------------- /src/077. Prime summations/077.rb: -------------------------------------------------------------------------------- 1 | require 'prime' 2 | 3 | def calc_ways(amount, coins) 4 | ways = [0] * (amount + 1) 5 | ways[0] = 1 6 | coins.each do |coin| 7 | coin.upto(amount) do |n| 8 | ways[n] += ways[n - coin] 9 | end 10 | end 11 | ways[amount] 12 | end 13 | 14 | primes = [] 15 | Prime.each(1000) {|p| primes << p} 16 | 17 | 10.upto(1000) do |amount| 18 | if calc_ways(amount, primes) > 5000 19 | puts amount 20 | break 21 | end 22 | end 23 | -------------------------------------------------------------------------------- /src/080. Square root digital expansion/080.rb: -------------------------------------------------------------------------------- 1 | require 'bigdecimal' 2 | require 'bigdecimal/math' 3 | 4 | class Integer 5 | def get_100_digits_sqrt 6 | sqrt = BigMath.sqrt(BigDecimal.new(self.to_s), 100).to_s 7 | match = /\.(\d{100})/.match(sqrt) 8 | if match 9 | match[1].chars.map(&:to_i).inject(:+) 10 | else 11 | 0 12 | end 13 | end 14 | end 15 | 16 | puts (1 .. 100).map(&:get_100_digits_sqrt).inject(:+) 17 | -------------------------------------------------------------------------------- /src/081. Path sum two ways/081.rb: -------------------------------------------------------------------------------- 1 | file_content = IO.read('p081_matrix.txt') 2 | 3 | matrix = [] 4 | file_content.lines do |line| 5 | matrix << line.split(',').map(&:to_i) 6 | end 7 | 8 | size = matrix.size 9 | 1.upto(size * 2 - 1) do |i| 10 | 0.upto(i) do |row| 11 | col = i - row 12 | if row >= size || col >= size 13 | next 14 | end 15 | if row == 0 || col == size - 1 16 | matrix[row][col] += matrix[row][col - 1] 17 | elsif col == 0 || row == size - 1 18 | matrix[row][col] += matrix[row - 1][col] 19 | else 20 | matrix[row][col] += [matrix[row - 1][col], matrix[row][col - 1]].min 21 | end 22 | end 23 | end 24 | 25 | puts matrix.last.last -------------------------------------------------------------------------------- /src/085. Counting rectangles/085.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | type Rectangle struct { 6 | m, n int 7 | } 8 | 9 | func (r *Rectangle) subRectNum() int { 10 | return r.m * r.n * (r.m + 1) * (r.n + 1) / 4 11 | } 12 | 13 | func main() { 14 | closest := &Rectangle{m : 0, n : 0} 15 | for m := 1; m <= 2000; m++ { 16 | for n := m; n <= 2000; n++ { 17 | rect := Rectangle{m, n} 18 | closest = subRectNumCloseTo2Million(closest, &rect) 19 | } 20 | } 21 | fmt.Println(closest.m * closest.n) 22 | } 23 | 24 | func subRectNumCloseTo2Million(r1 *Rectangle, r2 *Rectangle) *Rectangle { 25 | subRectNum1 := r1.subRectNum 26 | diff1 := subRectNum1() - 2000000 27 | if diff1 < 0 { 28 | diff1 = -diff1 29 | } 30 | subRectNum2 := r2.subRectNum 31 | diff2 := subRectNum2() - 2000000 32 | if diff2 < 0 { 33 | diff2 = -diff2 34 | } 35 | if diff1 < diff2 { 36 | return r1; 37 | } else { 38 | return r2; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/085. Counting rectangles/085.rb: -------------------------------------------------------------------------------- 1 | nearest = [0, 0] 2 | nearest_diff = 2_000_000 * 2_000_000 3 | 1.upto(2000) do |m| 4 | m.upto(2000) do |n| 5 | rectangle_num = m * n * (m + 1) * (n + 1) / 4 6 | diff = (rectangle_num - 2_000_000).abs 7 | if diff < nearest_diff 8 | nearest = [m, n] 9 | nearest_diff = diff 10 | end 11 | end 12 | end 13 | 14 | puts nearest[0] * nearest[1] 15 | -------------------------------------------------------------------------------- /src/087. Prime power triples/087.rb: -------------------------------------------------------------------------------- 1 | require 'prime' 2 | require 'set' 3 | 4 | upper_limit = 50_000_000 5 | 6 | prime_power2 = Prime.each(Math.sqrt(upper_limit)).to_a 7 | prime_power3 = prime_power2.take_while { |p| p < upper_limit ** (1.0 / 3) } 8 | prime_power4 = prime_power2.take_while { |p| p < upper_limit ** (1.0 / 4) } 9 | 10 | prime_triples = Set.new 11 | prime_power2.each do |p2| 12 | prime_power3.each do |p3| 13 | prime_power4.each do |p4| 14 | candidate = p2 ** 2 + p3 ** 3 + p4 ** 4 15 | prime_triples.add(candidate) if candidate <= upper_limit 16 | end 17 | end 18 | end 19 | 20 | puts prime_triples.size 21 | -------------------------------------------------------------------------------- /src/089. Roman numerals/089.lua: -------------------------------------------------------------------------------- 1 | function minimize_roman(r) 2 | return r:gsub("VIIII", "IX") 3 | :gsub("IIII", "IV") 4 | :gsub("LXXXX", "XL") 5 | :gsub("XXXX", "XC") 6 | :gsub("DCCCC", "CM") 7 | :gsub("CCCC", "CD") 8 | end 9 | 10 | local diff = 0 11 | for r in io.lines("p089_roman.txt") do 12 | diff = diff + (#r - #minimize_roman(r)) 13 | end 14 | print(diff) 15 | -------------------------------------------------------------------------------- /src/089. Roman numerals/089.rb: -------------------------------------------------------------------------------- 1 | def minimalize(original) 2 | minimal = String.new(original) 3 | minimal.gsub!(/VI{4}/, 'IX') 4 | minimal.gsub!(/I{4}/, 'IV') 5 | minimal.gsub!(/LX{4}/, 'XL') 6 | minimal.gsub!(/X{4}/, 'XC') 7 | minimal.gsub!(/DC{4}/, 'CM') 8 | minimal.gsub!(/C{4}/, 'CD') 9 | minimal 10 | end 11 | 12 | roman_file = File.read('p089_roman.txt') 13 | diff = 0 14 | roman_file.lines do |r| 15 | roman = r.chomp 16 | diff += roman.size - minimalize(roman).size 17 | end 18 | puts diff 19 | -------------------------------------------------------------------------------- /src/092. Square digit chains/092.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int chain(long long n); 6 | long long digit_square(long long n); 7 | 8 | std::unordered_set result_89; 9 | std::unordered_set result_1; 10 | 11 | int main() { 12 | int counter = 0; 13 | for (long long i = 1; i <= 10000000; ++i) { 14 | if (chain(i) == 89) { 15 | ++counter; 16 | } 17 | } 18 | std::cout << counter << std::endl; 19 | } 20 | 21 | int chain(long long n) { 22 | std::vector chain_result; 23 | while (true) { 24 | bool found_in_1 = result_1.find(n) != result_1.end(); 25 | if (n == 1 || found_in_1) { 26 | result_1.insert(chain_result.begin(), chain_result.end()); 27 | return 1; 28 | } 29 | bool found_in_89 = result_89.find(n) != result_89.end(); 30 | if (n == 89 || found_in_89) { 31 | result_89.insert(chain_result.begin(), chain_result.end()); 32 | return 89; 33 | } 34 | chain_result.push_back(n); 35 | n = digit_square(n); 36 | } 37 | } 38 | 39 | long long digit_square(long long n) { 40 | long long sum = 0; 41 | while (n > 0) { 42 | sum += (n % 10) * (n % 10); 43 | n /= 10; 44 | } 45 | return sum; 46 | } 47 | -------------------------------------------------------------------------------- /src/092. Square digit chains/092.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | var result1 = make(map[int]bool) 6 | var result89 = make(map[int]bool) 7 | 8 | func main() { 9 | counter := 0 10 | for i := 1; i <= 10000000; i++ { 11 | if (chain(i) == 89) { 12 | counter++ 13 | } 14 | } 15 | fmt.Println(counter) 16 | } 17 | 18 | func chain(n int) int { 19 | chainResult := make([]int, 0) 20 | for { 21 | if n == 1 || result1[n] { 22 | for _, r := range chainResult { 23 | result1[r] = true 24 | } 25 | return 1 26 | } 27 | if n == 89 || result89[n] { 28 | for _, r := range chainResult { 29 | result89[r] = true 30 | } 31 | return 89 32 | } 33 | chainResult = append(chainResult, n) 34 | n = digitSquare(n) 35 | } 36 | } 37 | 38 | func digitSquare(n int) int { 39 | sum := 0 40 | for n > 0 { 41 | sum += (n % 10) * (n % 10) 42 | n /= 10 43 | } 44 | return sum 45 | } 46 | -------------------------------------------------------------------------------- /src/092. Square digit chains/092.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.HashSet; 3 | import java.util.List; 4 | import java.util.Set; 5 | 6 | public class Main { 7 | 8 | private static final Set result89 = new HashSet<>(); 9 | private static final Set result1 = new HashSet<>(); 10 | 11 | public static void main(String[] args) { 12 | int counter = 0; 13 | for (long i = 1; i <= 10_000_000; i++) { 14 | if (chain(i) == 89) { 15 | counter++; 16 | } 17 | } 18 | System.out.println(counter); 19 | } 20 | 21 | private static long chain(long n) { 22 | List chainResults = new ArrayList<>(); 23 | while (true) { 24 | if (n == 1 || result1.contains(n)) { 25 | result1.addAll(chainResults); 26 | return 1; 27 | } 28 | if (n == 89 || result89.contains(n)) { 29 | result89.addAll(chainResults); 30 | return 89; 31 | } 32 | chainResults.add(n); 33 | n = digitSquare(n); 34 | } 35 | } 36 | 37 | private static long digitSquare(long n) { 38 | long sum = 0; 39 | while (n > 0) { 40 | sum += (n % 10) * (n % 10); 41 | n /= 10; 42 | } 43 | return sum; 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /src/092. Square digit chains/092.lua: -------------------------------------------------------------------------------- 1 | local chain_result = {} 2 | 3 | function sum_square(num) 4 | sum = 0 5 | while num > 0 do 6 | sum = sum + (num % 10) ^ 2 7 | num = math.floor(num / 10) 8 | end 9 | return sum 10 | end 11 | 12 | function chain(num) 13 | local t = {} 14 | local result 15 | while not chain_result[num] do 16 | if num == 1 or num == 89 then 17 | result = num 18 | break 19 | end 20 | table.insert(t, num) 21 | num = sum_square(num) 22 | end 23 | if not result then 24 | result = chain_result[num] 25 | end 26 | for k, v in ipairs(t) do 27 | chain_result[v] = result 28 | end 29 | return result 30 | end 31 | 32 | local count = 0 33 | for i = 1, 10000000 do 34 | if chain(i) == 89 then 35 | count = count + 1 36 | end 37 | end 38 | 39 | print(count) -------------------------------------------------------------------------------- /src/097. Large non-Mersenne prime/097.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "math/big" 6 | ) 7 | 8 | func main() { 9 | var m big.Int 10 | m.Exp(big.NewInt(10), big.NewInt(10), nil) 11 | 12 | var result big.Int 13 | result.Exp(big.NewInt(2), big.NewInt(7830457), &m) 14 | result.Mul(big.NewInt(28433), &result) 15 | result.Add(&result, big.NewInt(1)) 16 | result.Mod(&result, &m) 17 | 18 | fmt.Println(result.String()) 19 | } 20 | -------------------------------------------------------------------------------- /src/097. Large non-Mersenne prime/097.hs: -------------------------------------------------------------------------------- 1 | main = print $ (28433 * 2^7830457 + 1) `mod` 10^10 2 | -------------------------------------------------------------------------------- /src/097. Large non-Mersenne prime/097.java: -------------------------------------------------------------------------------- 1 | import java.math.BigInteger; 2 | 3 | public class Main { 4 | public static void main(String[] args) { 5 | final BigInteger ten2Ten = BigInteger.valueOf(10).pow(10); 6 | BigInteger powerTwo = BigInteger.valueOf(2).modPow(BigInteger.valueOf(7830457), ten2Ten); 7 | BigInteger prime = powerTwo.multiply(BigInteger.valueOf(28433)).add(BigInteger.ONE); 8 | BigInteger result = prime.mod(ten2Ten); 9 | System.out.println(result); 10 | } 11 | } 12 | 13 | -------------------------------------------------------------------------------- /src/097. Large non-Mersenne prime/097.py: -------------------------------------------------------------------------------- 1 | print((28433 * 2 ** 7830457 + 1) % (10 ** 10)) 2 | -------------------------------------------------------------------------------- /src/097. Large non-Mersenne prime/097.rb: -------------------------------------------------------------------------------- 1 | puts (28433 * 2 ** 7830457 + 1) % 10 ** 10 -------------------------------------------------------------------------------- /src/099. Largest exponential/099.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #define LINE_LEN 100 6 | 7 | int main(void) { 8 | FILE *f = fopen("p099_base_exp.txt", "r"); 9 | char line[LINE_LEN]; 10 | double max_power = 0; 11 | int max_line_no = 0; 12 | int line_no = 0; 13 | while (fgets(line, sizeof(line), f)) { 14 | line_no += 1; 15 | int base, exp; 16 | sscanf(line, "%d,%d", &base, &exp); 17 | double current_power = exp * log((double)base); 18 | if (current_power > max_power) { 19 | max_power = current_power; 20 | max_line_no = line_no; 21 | } 22 | } 23 | printf("%d\n", max_line_no); 24 | } 25 | -------------------------------------------------------------------------------- /src/099. Largest exponential/099.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | int main() { 8 | std::ifstream f("p099_base_exp.txt"); 9 | std::string line; 10 | double max_power = 0; 11 | int max_line_no = 0; 12 | int line_no = 0; 13 | while (std::getline(f, line)) { 14 | line_no += 1; 15 | std::istringstream line_stream(line); 16 | std::string base_str, exp_str; 17 | std::getline(line_stream, base_str, ','); 18 | std::getline(line_stream, exp_str); 19 | int base, exp; 20 | base = std::stoi(base_str); 21 | exp = std::stoi(exp_str); 22 | double current_power = exp * std::log(base); 23 | if (current_power > max_power) { 24 | max_power = current_power; 25 | max_line_no = line_no; 26 | } 27 | } 28 | std::cout << max_line_no << std::endl; 29 | } 30 | -------------------------------------------------------------------------------- /src/099. Largest exponential/099.lua: -------------------------------------------------------------------------------- 1 | local max = 0 2 | local max_line_no = 0 3 | 4 | local f = io.open("p099_base_exp.txt") 5 | local line_no = 1 6 | for line in f:lines() do 7 | local base, exp = line:match("^(%d+),(%d+)$") 8 | base, exp = tonumber(base), tonumber(exp) 9 | current = exp * math.log(base) 10 | if current > max then 11 | max = current 12 | max_line_no = line_no 13 | end 14 | line_no = line_no + 1 15 | end 16 | 17 | print(max_line_no) -------------------------------------------------------------------------------- /src/099. Largest exponential/099.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | max_line_no = 0 4 | 5 | with open("p099_base_exp.txt") as f: 6 | line_no = 1 7 | max = 0 8 | for line in f: 9 | base, exp = map(int, line.split(',')) 10 | current = exp * math.log(base) 11 | if current > max: 12 | max = current 13 | max_line_no = line_no 14 | line_no += 1 15 | 16 | print(max_line_no) 17 | -------------------------------------------------------------------------------- /src/099. Largest exponential/099.rb: -------------------------------------------------------------------------------- 1 | max = 0 2 | max_line_no = 0 3 | 4 | File.open("p099_base_exp.txt") do |file| 5 | line_no = 1 6 | while line = file.gets 7 | md = line.match(/^(\d+),(\d+)$/) 8 | base, exp = md[1].to_i, md[2].to_i 9 | current = exp * Math.log(base) 10 | if current > max 11 | max = current 12 | max_line_no = line_no 13 | end 14 | line_no += 1 15 | end 16 | end 17 | 18 | puts max_line_no -------------------------------------------------------------------------------- /src/102. Triangle containment/102.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | "fmt" 6 | "log" 7 | "math" 8 | "os" 9 | "strconv" 10 | "strings" 11 | ) 12 | 13 | type Point struct { 14 | X, Y float64 15 | } 16 | 17 | type Triangle struct { 18 | A, B, C Point 19 | } 20 | 21 | func main() { 22 | origin := Point{0, 0} 23 | triangles := readTrianglesFromFile("p102_triangles.txt") 24 | count := 0 25 | for _, tri := range triangles { 26 | if isPointInsideTriangle(tri, origin) { 27 | count++ 28 | } 29 | } 30 | fmt.Println(count) 31 | } 32 | 33 | func isPointInsideTriangle(tri Triangle, p Point) bool { 34 | areaABC := triangleArea(tri) 35 | a, b, c := tri.A, tri.B, tri.C 36 | areaABP := triangleArea(Triangle{a, b, p}) 37 | areaBCP := triangleArea(Triangle{b, c, p}) 38 | areaCAP := triangleArea(Triangle{c, a, p}) 39 | return areaABC == areaABP + areaBCP + areaCAP 40 | } 41 | 42 | // https://en.wikipedia.org/wiki/Triangle#Using_coordinates 43 | func triangleArea(tri Triangle) float64 { 44 | return math.Abs((tri.A.X * tri.B.Y - tri.A.X * tri.C.Y + 45 | tri.B.X * tri.C.Y - tri.B.X * tri.A.Y + 46 | tri.C.X * tri.A.Y - tri.C.X * tri.B.Y) / 2) 47 | } 48 | 49 | func readTrianglesFromFile(fileName string) []Triangle { 50 | f, err := os.Open(fileName) 51 | if err != nil { 52 | log.Fatal("err") 53 | } 54 | defer f.Close() 55 | 56 | scanner := bufio.NewScanner(f) 57 | var triangles []Triangle 58 | for scanner.Scan() { 59 | coordinates := strings.Split(scanner.Text(), ",") 60 | var tri Triangle 61 | tri.A = buildPoint(coordinates[0:2]) 62 | tri.B = buildPoint(coordinates[2:4]) 63 | tri.C = buildPoint(coordinates[4:6]) 64 | triangles = append(triangles, tri) 65 | } 66 | return triangles 67 | } 68 | 69 | func buildPoint(coordinates []string) Point { 70 | coordX, _ := strconv.ParseFloat(coordinates[0], 64) 71 | coordY, _ := strconv.ParseFloat(coordinates[1], 64) 72 | return Point{coordX, coordY} 73 | } 74 | -------------------------------------------------------------------------------- /src/104. Pandigital Fibonacci ends/104.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | # assumes n is an integer with at most 9 digits 4 | def pandigital(n): 5 | if n < 10 ** 8: 6 | return False 7 | digits = set() 8 | for i in range(9): 9 | n, d = divmod(n, 10) 10 | if d == 0: 11 | return False 12 | if d in digits: 13 | return False 14 | else: 15 | digits.add(d) 16 | return True 17 | 18 | def begins_pandigital(n): 19 | return pandigital(int(str(n)[0:9])) 20 | 21 | def ends_pandigital(n): 22 | return pandigital(n % 10 ** 10) 23 | 24 | k = 2 25 | fa, fb = 1, 1 26 | while True: 27 | fa, fb = fb, fa + fb 28 | k += 1 29 | if ends_pandigital(fb) and begins_pandigital(fb): 30 | print(k) 31 | break 32 | -------------------------------------------------------------------------------- /src/104. Pandigital Fibonacci ends/104.rb: -------------------------------------------------------------------------------- 1 | require 'set' 2 | 3 | class Integer 4 | def pandigital? 5 | return false if self < 100_000_000 6 | digits = Set.new 7 | n = self 8 | 9.times do 9 | n, d = n.divmod(10) 10 | return false if d == 0 11 | if digits.include? d 12 | return false 13 | else 14 | digits << d 15 | end 16 | end 17 | true 18 | end 19 | 20 | def begins_pandigital? 21 | self.to_s[0, 9].to_i.pandigital? 22 | end 23 | 24 | def ends_pandigital? 25 | (self % 1_000_000_000).pandigital? 26 | end 27 | end 28 | 29 | k = 2 30 | fa, fb = 1, 1 31 | while true 32 | fa, fb = fb, fa + fb 33 | k += 1 34 | if fb.ends_pandigital? and fb.begins_pandigital? 35 | puts k 36 | break 37 | end 38 | end -------------------------------------------------------------------------------- /src/112. Bouncy numbers/112.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using std::string; 6 | 7 | bool is_bouncy(long long n); 8 | 9 | int main() { 10 | long long bouncy_count = 0; 11 | long long n = 1; 12 | while (true) { 13 | if (is_bouncy(n)) { 14 | ++bouncy_count; 15 | } 16 | if (static_cast(bouncy_count) / n == 0.99) { 17 | std::cout << n << std::endl; 18 | break; 19 | } 20 | ++n; 21 | } 22 | } 23 | 24 | bool is_bouncy(long long n) { 25 | string original = std::to_string(n); 26 | string sorted(original); 27 | std::sort(sorted.begin(), sorted.end()); 28 | if (original == sorted) { 29 | return false; 30 | } 31 | std::reverse(sorted.begin(), sorted.end()); 32 | if (original == sorted) { 33 | return false; 34 | } 35 | return true; 36 | } 37 | -------------------------------------------------------------------------------- /src/112. Bouncy numbers/112.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "sort" 6 | "strconv" 7 | "strings" 8 | ) 9 | 10 | func main() { 11 | bouncyCount := 0 12 | n := 1 13 | for { 14 | if isBouncy(n) { 15 | bouncyCount++ 16 | } 17 | if float64(bouncyCount) / float64(n) == 0.99 { 18 | fmt.Println(n) 19 | break 20 | } 21 | n++ 22 | } 23 | } 24 | 25 | func isBouncy(n int) bool { 26 | original := strconv.Itoa(n) 27 | chars := strings.Split(original, "") 28 | sort.Strings(chars) 29 | sorted := strings.Join(chars, "") 30 | if original == sorted { 31 | return false 32 | } 33 | 34 | for i, j := 0, len(chars) - 1; i < j; i, j = i + 1, j - 1 { 35 | chars[i], chars[j] = chars[j], chars[i] 36 | } 37 | reversed := strings.Join(chars, "") 38 | if original == reversed { 39 | return false 40 | } 41 | return true 42 | } 43 | -------------------------------------------------------------------------------- /src/112. Bouncy numbers/112.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | public class Main { 4 | 5 | public static void main(String[] args) { 6 | long bouncyCount = 0; 7 | long n = 1; 8 | while (true) { 9 | if (isBouncy(n)) { 10 | ++bouncyCount; 11 | } 12 | if ((double) bouncyCount / n == 0.99) { 13 | System.out.println(n); 14 | break; 15 | } 16 | n++; 17 | } 18 | } 19 | 20 | private static boolean isBouncy(long n) { 21 | String original = Long.toString(n); 22 | String sorted = sortString(original); 23 | if (original.equals(sorted)) { 24 | return false; 25 | } 26 | sorted = reverseString(sorted); 27 | if (original.equals(sorted)) { 28 | return false; 29 | } 30 | return true; 31 | } 32 | 33 | private static String sortString(String original) { 34 | char[] chars = original.toCharArray(); 35 | Arrays.sort(chars); 36 | return new String(chars); 37 | } 38 | 39 | private static String reverseString(String original) { 40 | return new StringBuilder(original).reverse().toString(); 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /src/112. Bouncy numbers/112.rb: -------------------------------------------------------------------------------- 1 | class Integer 2 | def bouncy? 3 | if self.to_s.scan(/\d/).sort.join.to_i == self or self.to_s.scan(/\d/).sort.reverse.join.to_i == self 4 | false 5 | else 6 | true 7 | end 8 | end 9 | end 10 | 11 | count = 0.0 12 | n = 1 13 | while true 14 | count += 1 if n.bouncy? 15 | if count / n == 0.99 16 | puts n 17 | break 18 | end 19 | n += 1 20 | end 21 | -------------------------------------------------------------------------------- /src/113. Non-bouncy numbers/113.lua: -------------------------------------------------------------------------------- 1 | local digit_max = 100 2 | 3 | -- increasing numbers, the index is number of digits 4 | local inc = {} 5 | inc[1] = {} 6 | for d = 1, 9 do 7 | inc[1][d] = 1 8 | end 9 | for e = 2, digit_max do 10 | inc[e] = {} 11 | for d = 1, 9 do 12 | inc[e][d] = 0 13 | for s = d, 9 do 14 | inc[e][d] = inc[e][d] + inc[e - 1][s] 15 | end 16 | end 17 | end 18 | 19 | -- decreasing numbers 20 | local dec = {} 21 | dec[1] = {} 22 | dec[1][0] = 0 23 | for d = 1, 9 do 24 | dec[1][d] = 1 25 | end 26 | for e = 2, digit_max do 27 | dec[e] = {} 28 | dec[e][0] = 0 29 | for d = 1, 9 do 30 | dec[e][d] = 1 -- followed by all zero digits 31 | for s = 0, d do 32 | dec[e][d] = dec[e][d] + dec[e - 1][s] 33 | end 34 | end 35 | end 36 | 37 | local bouncy_count = 0 38 | for e = 1, digit_max do 39 | for _, v in ipairs(inc[e]) do 40 | bouncy_count = bouncy_count + v 41 | end 42 | for k, v in pairs(dec[e]) do 43 | bouncy_count = bouncy_count + v 44 | end 45 | -- numbers with all equal digits are both increasing and decreasing 46 | bouncy_count = bouncy_count - 9 47 | end 48 | 49 | print(bouncy_count) 50 | -------------------------------------------------------------------------------- /src/113. Non-bouncy numbers/113.py: -------------------------------------------------------------------------------- 1 | digit_max = 100 2 | 3 | # increasing numbers, the index is number of digits 4 | inc = [] 5 | inc.append([]) 6 | inc.append([0] + [1] * 9) 7 | for e in range(2, digit_max + 1): 8 | inc.append([0]) 9 | for d in range(1, 10): 10 | inc[e].append(sum(inc[e - 1][d:10])) 11 | 12 | # decreasing numbers 13 | dec = [] 14 | dec.append([]) 15 | dec.append([0] + [1] * 9) 16 | for e in range(2, digit_max + 1): 17 | dec.append([0]) 18 | for d in range(1, 10): 19 | dec[e].append(sum(dec[e - 1][0:(d + 1)]) + 1) 20 | 21 | bouncy_count = 0 22 | for e in range(1, digit_max + 1): 23 | # numbers with all equal digits are both increasing and decreasing 24 | bouncy_count += sum(inc[e]) + sum(dec[e]) - 9 25 | 26 | print(bouncy_count) 27 | -------------------------------------------------------------------------------- /src/113. Non-bouncy numbers/113.rb: -------------------------------------------------------------------------------- 1 | digit_max = 100 2 | 3 | # increasing numbers, the index is number of digits 4 | inc = [] 5 | inc[0] = [] 6 | inc[1] = [0] + [1] * 9 7 | 2.upto(digit_max) do |e| 8 | inc[e] = [0] 9 | 1.upto(9) do |d| 10 | inc[e][d] = inc[e - 1][d, 10 - d].inject(:+) 11 | end 12 | end 13 | 14 | # decreasing numbers 15 | dec = [] 16 | dec[0] = [] 17 | dec[1] = [0] + [1] * 9 18 | 2.upto(digit_max) do |e| 19 | dec[e] = [0] 20 | 1.upto(9) do |d| 21 | dec[e][d] = dec[e - 1][0, d + 1].inject(:+) + 1 22 | end 23 | end 24 | 25 | bouncy_count = 0 26 | 1.upto(digit_max) do |e| 27 | # numbers with all equal digits are both increasing and decreasing 28 | bouncy_count += inc[e].inject(:+) + dec[e].inject(:+) - 9 29 | end 30 | puts bouncy_count 31 | -------------------------------------------------------------------------------- /src/116. Red, green or blue tiles/116.java: -------------------------------------------------------------------------------- 1 | import java.math.BigInteger; 2 | 3 | public class Main { 4 | 5 | private static final int UPPER_LIMIT = 50; 6 | private static final BigInteger[] FACTORIALS = new BigInteger[UPPER_LIMIT + 1]; 7 | 8 | static { 9 | FACTORIALS[0] = BigInteger.ONE; 10 | for (int i = 1; i <= UPPER_LIMIT; i++) { 11 | FACTORIALS[i] = FACTORIALS[i - 1].multiply(BigInteger.valueOf(i)); 12 | } 13 | } 14 | 15 | public static void main(String[] args) { 16 | BigInteger red = BigInteger.ZERO; 17 | for (int r = 1; r <= UPPER_LIMIT / 2; r++) { 18 | int n = UPPER_LIMIT - r; 19 | red = red.add(choose(n, r)); 20 | } 21 | 22 | BigInteger green = BigInteger.ZERO; 23 | for (int g = 1; g <= UPPER_LIMIT / 3; g++) { 24 | int n = UPPER_LIMIT - 2 * g; 25 | green = green.add(choose(n, g)); 26 | } 27 | 28 | BigInteger blue = BigInteger.ZERO; 29 | for (int b = 1; b <= UPPER_LIMIT / 4; b++) { 30 | int n = UPPER_LIMIT - 3 * b; 31 | blue = blue.add(choose(n, b)); 32 | } 33 | 34 | BigInteger total = red.add(green).add(blue); 35 | System.out.println(total.longValue()); 36 | 37 | } 38 | 39 | private static BigInteger choose(int n, int k) { 40 | return FACTORIALS[n].divide(FACTORIALS[n - k]).divide(FACTORIALS[k]); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/116. Red, green or blue tiles/116.py: -------------------------------------------------------------------------------- 1 | upper_limit = 50 2 | factorials = [1] 3 | for n in range(1, upper_limit + 1): 4 | factorials.append(factorials[n - 1] * n) 5 | 6 | def choose(n, k): 7 | global factorials 8 | return factorials[n] // factorials[n - k] // factorials[k] 9 | 10 | red, green, blue = 0, 0, 0 11 | for r in range(1, upper_limit // 2 + 1): 12 | n = upper_limit - r 13 | red += choose(n, r) 14 | 15 | for g in range(1, upper_limit // 3 + 1): 16 | n = upper_limit - 2 * g 17 | green += choose(n, g) 18 | 19 | for b in range(1, upper_limit // 4 + 1): 20 | n = upper_limit - 3 * b 21 | blue += choose(n, b) 22 | 23 | print(red + green + blue) 24 | -------------------------------------------------------------------------------- /src/116. Red, green or blue tiles/116.rb: -------------------------------------------------------------------------------- 1 | upper_limit = 50 2 | $factorials = [1] 3 | 1.upto(upper_limit) do |n| 4 | $factorials[n] = $factorials[n - 1] * n 5 | end 6 | 7 | def choose(n, k) 8 | $factorials[n] / $factorials[n - k] / $factorials[k] 9 | end 10 | 11 | red, green, blue = 0, 0, 0 12 | 1.upto(upper_limit / 2) do |r| 13 | n = upper_limit - r 14 | red += choose(n, r) 15 | end 16 | 17 | 1.upto(upper_limit / 3) do |g| 18 | n = upper_limit - 2 * g 19 | green += choose(n, g) 20 | end 21 | 22 | 1.upto(upper_limit / 4) do |b| 23 | n = upper_limit - 3 * b 24 | blue += choose(n, b) 25 | end 26 | 27 | puts red + green + blue 28 | -------------------------------------------------------------------------------- /src/119. Digit power sum/119.py: -------------------------------------------------------------------------------- 1 | def sum_digits(n): 2 | sum = 0 3 | while n > 0: 4 | sum += n % 10 5 | n /= 10 6 | return sum 7 | 8 | # guess 9 | upper_limit_power = 15 10 | upper_limit = 10 ** upper_limit_power 11 | digit_sum_powers = [] 12 | n = 2 13 | for n in range(2, 9 * upper_limit_power): 14 | n_power = n 15 | while n_power < upper_limit: 16 | if n_power >= 10 and sum_digits(n_power) == n: 17 | digit_sum_powers.append(n_power) 18 | n_power *= n 19 | 20 | # if less than 30, take a bigger guess of upper_limit_power 21 | if len(digit_sum_powers) >= 30: 22 | digit_sum_powers.sort() 23 | print(digit_sum_powers[29]) 24 | -------------------------------------------------------------------------------- /src/119. Digit power sum/119.rb: -------------------------------------------------------------------------------- 1 | class Integer 2 | def sum_digits 3 | self.to_s.chars.map(&:to_i).inject(:+) 4 | end 5 | end 6 | 7 | # guess 8 | upper_limit_power = 15 9 | upper_limit = 10 ** upper_limit_power 10 | digit_sum_powers = [] 11 | 2.upto(9 * upper_limit_power) do |n| 12 | n_power = n 13 | while n_power < upper_limit 14 | if n_power >= 10 and n_power.sum_digits == n 15 | digit_sum_powers << n_power 16 | end 17 | n_power *= n 18 | end 19 | end 20 | 21 | # if less than 30, take a bigger guess of upper_limit_power 22 | if digit_sum_powers.size >= 30 23 | digit_sum_powers.sort! 24 | puts digit_sum_powers[29] 25 | end 26 | -------------------------------------------------------------------------------- /src/120. Square remainders/120.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | sum := 0 7 | for a := 3; a <= 1000; a++ { 8 | sum += rMax(a) 9 | } 10 | fmt.Println(sum) 11 | } 12 | 13 | // From the Binomial Theorem 14 | // (((a - 1)^n + (a + 1)^n)) % a^2 15 | // = (na(-1)^(n - 1) + (-1)^n) % a^2 16 | // = 2na % a^2 when n is odd 17 | // = 2 % a^2 when n is even 18 | // So the maximum of r is 2na in which 2n < a, or a * (maximum even number smaller than a) 19 | func rMax(a int) int { 20 | if a % 2 == 0 { 21 | return a * (a - 2) 22 | } else { 23 | return a * (a - 1) 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/120. Square remainders/120.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | 3 | public static void main(String[] args) { 4 | long sum = 0; 5 | for (int a = 3; a <= 1000; a++) { 6 | sum += rMax(a); 7 | } 8 | System.out.println(sum); 9 | } 10 | 11 | // From the Binomial Theorem 12 | // (((a - 1)^n + (a + 1)^n)) % a^2 13 | // = (na(-1)^(n - 1) + (-1)^n) % a^2 14 | // = 2na % a^2 when n is odd 15 | // = 2 % a^2 when n is even 16 | // So the maximum of r is 2na in which 2n < a, or a * (maximum even number smaller than a) 17 | private static long rMax(int a){ 18 | if (a % 2 == 0) { 19 | return a * (a - 2); 20 | } else { 21 | return a * (a - 1); 22 | } 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /src/120. Square remainders/120.py: -------------------------------------------------------------------------------- 1 | # From the Binomial Theorem 2 | # (((a - 1)^n + (a + 1)^n)) % a^2 3 | # = (na(-1)^(n - 1) + (-1)^n) % a^2 4 | # = 2na % a^2 when n is odd 5 | # = 2 % a^2 when n is even 6 | # So the maximum of r is 2na in which 2n < a, or a * (maximum even number smaller than a) 7 | 8 | def r_max(a): 9 | if a % 2 == 0: 10 | return a * (a - 2) 11 | else: 12 | return a * (a - 1) 13 | 14 | sum = 0 15 | for a in range(3, 1001): 16 | sum += r_max(a) 17 | print(sum) 18 | -------------------------------------------------------------------------------- /src/120. Square remainders/120.rb: -------------------------------------------------------------------------------- 1 | # From the Binomial Theorem 2 | # (((a - 1)^n + (a + 1)^n)) % a^2 3 | # = (na(-1)^(n - 1) + (-1)^n) % a^2 4 | # = 2na % a^2 when n is odd 5 | # = 2 % a^2 when n is even 6 | # So the maximum of r is 2na in which 2n < a, or a * (maximum even number smaller than a) 7 | 8 | class Integer 9 | def r_max() 10 | if self % 2 == 0 11 | self * (self - 2) 12 | else 13 | self * (self - 1) 14 | end 15 | end 16 | end 17 | 18 | puts (3 .. 1000).to_a.map(&:r_max).inject(:+) 19 | -------------------------------------------------------------------------------- /src/123. Prime square remainders/123.rb: -------------------------------------------------------------------------------- 1 | require 'prime' 2 | 3 | # From the Binomial Theorem 4 | # (((p - 1)^n + (p + 1)^n)) % p^2 5 | # = (np(-1)^(n - 1) + (-1)^n) % p^2 6 | # = 2np % p^2 when n is odd 7 | # = 2 when n is even 8 | def square_remainder(n, p) 9 | 2 * n * p % (p * p) 10 | end 11 | 12 | n = 1 13 | Prime.each do |p| 14 | if n.even? 15 | n += 1 16 | next 17 | end 18 | if square_remainder(n, p) > 10 ** 10 19 | puts n 20 | break 21 | end 22 | n += 1 23 | end 24 | -------------------------------------------------------------------------------- /src/125. Palindromic sums/125.py: -------------------------------------------------------------------------------- 1 | def is_palindrome(n): 2 | return str(n)[::-1] == str(n) 3 | 4 | squares = [0] 5 | for i in range(1, 10 ** 4): 6 | squares.append(i * i) 7 | 8 | result = set() 9 | for i in range(1, len(squares)): 10 | n = squares[i] 11 | for j in range(i + 1, len(squares)): 12 | n += squares[j] 13 | if n > 10 ** 8: 14 | break 15 | if is_palindrome(n): 16 | result.add(n) 17 | 18 | print(sum(result)) 19 | -------------------------------------------------------------------------------- /src/125. Palindromic sums/125.rb: -------------------------------------------------------------------------------- 1 | require 'set' 2 | 3 | class Integer 4 | def palindrome? 5 | self.to_s.reverse == self.to_s 6 | end 7 | end 8 | 9 | squares = [0] 10 | 1.upto(10 ** 4) {|i| squares << i * i} 11 | 12 | result = Set.new 13 | 1.upto(squares.size - 1) do |i| 14 | sum = squares[i] 15 | (i + 1).upto(squares.size - 1) do |j| 16 | sum += squares[j] 17 | break if sum > 10 ** 8 18 | result.add(sum) if sum.palindrome? 19 | end 20 | end 21 | puts result.each.inject(:+) 22 | -------------------------------------------------------------------------------- /src/145. How many reversible numbers are there below one-billion/145.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | static int reversible_count(int d); 5 | 6 | int main(void) { 7 | int count = 0; 8 | for (int d = 1; d <= 9; ++d) { 9 | count += reversible_count(d); 10 | } 11 | printf("%d\n", count); 12 | return 0; 13 | } 14 | 15 | static int reversible_count(int d) { 16 | switch (d % 4) { 17 | case 1: 18 | // no solutions 19 | return 0; 20 | case 0: 21 | case 2: 22 | // 2 digits: no carry over, and sum of two digits is odd 23 | // 2 digits => 20 24 | // 4 digits: outer pair is the same as 2 digits 25 | // inner pair has 30 possibilities because 0 is allowed 26 | return 20 * (int)pow(30 , d / 2 - 1); 27 | case 3: 28 | // the first and third digit must be odd and gives carry over: 20 possibilities 29 | // middle digit: add to itself, no carry over: 5 possibilities 30 | // 4 digits: same as before, no leading zero 31 | return 100 * (int)pow(500, (d - 3) / 4); 32 | } 33 | return 0; 34 | } 35 | -------------------------------------------------------------------------------- /src/145. How many reversible numbers are there below one-billion/145.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | static int reversible_count(int d); 5 | 6 | int main() { 7 | int count = 0; 8 | for (int d = 1; d <= 9; ++d) { 9 | count += reversible_count(d); 10 | } 11 | std::cout << count << std::endl; 12 | } 13 | 14 | static int reversible_count(int d) { 15 | switch (d % 4) { 16 | case 1: 17 | // no solutions 18 | return 0; 19 | case 0: 20 | case 2: 21 | // 2 digits: no carry over, and sum of two digits is odd 22 | // 2 digits => 20 23 | // 4 digits: outer pair is the same as 2 digits 24 | // inner pair has 30 possibilities because 0 is allowed 25 | return 20 * std::pow(30 , d / 2 - 1); 26 | case 3: 27 | // the first and third digit must be odd and gives carry over: 20 possibilities 28 | // middle digit: add to itself, no carry over: 5 possibilities 29 | // 4 digits: same as before, no leading zero 30 | return 100 * std::pow(500, (d - 3) / 4); 31 | } 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /src/145. How many reversible numbers are there below one-billion/145.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "math" 6 | ) 7 | 8 | func main() { 9 | count := 0 10 | for d := 1; d <= 9; d++ { 11 | count += reversible_count(d) 12 | } 13 | fmt.Println(count) 14 | } 15 | 16 | func reversible_count(d int) int { 17 | switch d % 4 { 18 | case 1: 19 | // no solutions 20 | return 0 21 | case 0: 22 | fallthrough 23 | case 2: 24 | // 2 digits: no carry over, and sum of two digits is odd 25 | // 2 digits => 20 26 | // 4 digits: outer pair is the same as 2 digits 27 | // inner pair has 30 possibilities because 0 is allowed 28 | return 20 * int(math.Pow(30 , float64(d / 2 - 1))) 29 | case 3: 30 | // the first and third digit must be odd and gives carry over: 20 possibilities 31 | // middle digit: add to itself, no carry over: 5 possibilities 32 | // 4 digits: same as before, no leading zero 33 | return 100 * int(math.Pow(500, float64(d - 3) / 4)) 34 | } 35 | return 0 36 | } 37 | -------------------------------------------------------------------------------- /src/145. How many reversible numbers are there below one-billion/145.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | 3 | public static void main(String[] args) { 4 | int count = 0; 5 | for (int d = 1; d <= 9; d++) { 6 | count += reversibleCount(d); 7 | } 8 | System.out.println(count); 9 | } 10 | 11 | private static long reversibleCount(int d) { 12 | switch (d % 4) { 13 | case 1: 14 | // no solutions 15 | return 0; 16 | case 0: 17 | case 2: 18 | // 2 digits: no carry over, and sum of two digits is odd 19 | // 2 digits => 20 20 | // 4 digits: outer pair is the same as 2 digits 21 | // inner pair has 30 possibilities because 0 is allowed 22 | return 20 * (long) Math.pow(30 , d / 2 - 1); 23 | case 3: 24 | // the first and third digit must be odd and gives carry over: 20 possibilities 25 | // middle digit: add to itself, no carry over: 5 possibilities 26 | // 4 digits: same as before, no leading zero 27 | return 100 * (long) Math.pow(500, (d - 3) / 4); 28 | } 29 | return 0; 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/145. How many reversible numbers are there below one-billion/145.lua: -------------------------------------------------------------------------------- 1 | function reversible_count(d) 2 | if d % 4 == 1 then 3 | return 0 4 | end 5 | -- 2 digits: no carry over, and sum of two digits is odd 6 | -- 2 digits => 20 7 | -- 4 digits: outer pair is the same as 2 digits 8 | -- inner pair has 30 possibilities because 0 is allowed 9 | if d % 4 == 0 or d % 4 == 2 then 10 | return 20 * 30 ^ (d / 2 - 1) 11 | end 12 | -- the first and third digit must be odd and gives carry over: 20 possibilities 13 | -- middle digit: add to itself, no carry over: 5 possibilities 14 | -- 4 digits: same as before, no leading zero 15 | if d % 4 == 3 then 16 | return 100 * 500 ^ ((d - 3) / 4) 17 | end 18 | end 19 | 20 | local count = 0 21 | for d = 1, 9 do 22 | count = count + reversible_count(d) 23 | end 24 | print(string.format("%d", count)) 25 | -------------------------------------------------------------------------------- /src/145. How many reversible numbers are there below one-billion/145.py: -------------------------------------------------------------------------------- 1 | def reversible_count(d): 2 | if d % 4 == 1: 3 | return 0 4 | # 2 digits: no carry over, and sum of two digits is odd 5 | # 2 digits => 20 6 | # 4 digits: outer pair is the same as 2 digits 7 | # inner pair has 30 possibilities because 0 is allowed 8 | if d % 4 == 0 or d % 4 == 2: 9 | return 20 * 30 ** (d // 2 - 1) 10 | # the first and third digit must be odd and gives carry over: 20 possibilities 11 | # middle digit: add to itself, no carry over: 5 possibilities 12 | # 4 digits: same as before, no leading zero 13 | if d % 4 == 3: 14 | return 100 * 500 ** ((d - 3) // 4) 15 | 16 | print(sum([reversible_count(d) for d in range(1, 10)])) 17 | -------------------------------------------------------------------------------- /src/145. How many reversible numbers are there below one-billion/145.rb: -------------------------------------------------------------------------------- 1 | def reversible_count(d) 2 | case d % 4 3 | when 1 then 0 4 | # 2 digits: no carry over, and sum of two digits is odd 5 | # 2 digits => 20 6 | # 4 digits: outer pair is the same as 2 digits 7 | # inner pair has 30 possibilities because 0 is allowed 8 | when 0, 2 then 20 * 30 ** (d / 2 - 1) 9 | # the first and third digit must be odd and gives carry over: 20 possibilities 10 | # middle digit: add to itself, no carry over: 5 possibilities 11 | # 4 digits: same as before, no leading zero 12 | when 3 then 100 * 500 ** ((d - 3) / 4) 13 | end 14 | end 15 | 16 | puts (1 .. 9).map{|d| reversible_count(d)}.inject(:+) 17 | -------------------------------------------------------------------------------- /src/146. Investigating a Prime Pattern/146.rb: -------------------------------------------------------------------------------- 1 | require 'prime' 2 | 3 | upper_limit = 150_000_000 4 | $primes = [] 5 | Prime.each(upper_limit + 1) {|p| $primes << p} 6 | $primes.shift # 2 is not needed 7 | 8 | def if_prime_pattern(n) 9 | return false if n % 3 == 0 10 | return false if n % 7 == 0 11 | return false if n % 13 == 0 12 | 13 | # (n^2 + 13) % 7 == 0 14 | return false if n % 7 == 1 or n % 7 == 6 15 | # (n^2 + 3) % 7 == 0 16 | return false if n % 7 == 2 or n % 7 == 5 17 | # (n^2 + 9) % 13 == 0 18 | return false if n % 13 == 2 or n % 13 == 11 19 | # (n^2 + 1) % 13 == 0 20 | return false if n % 13 == 5 or n % 13 == 8 21 | # (n^2 + 3) % 13 == 0 22 | return false if n % 13 == 6 or n % 13 == 7 23 | 24 | $primes.each do |p| 25 | break if p > n + 1 26 | [1, 3, 7, 9, 13, 27].each do |a| 27 | return false if (n * n + a) % p == 0 28 | end 29 | end 30 | 31 | # tests above primes are consecutive 32 | [5, 11, 15, 17, 19, 21, 23, 25].each do |b| 33 | $primes.each do |p| 34 | # tests up to the biggest prime less than the square root of n * n + 25 35 | # the condition p > n + 1 works for 10, and certainly works for big enough n 36 | return false if p > n + 1 37 | break if (n * n + b) % p == 0 38 | end 39 | end 40 | true 41 | end 42 | 43 | sum = 0 44 | # obviously n must be even 45 | # n must be multiples of 5 because 46 | # if n = 5k + 1 or 5k + 4, n^2 + 9 is divisible by 5 47 | # if n = 5k + 2 or 5k + 3, n^2 + 1 is divisible by 5 48 | 10.step(upper_limit, 10) do |n| 49 | sum += n if if_prime_pattern(n) 50 | end 51 | puts sum 52 | -------------------------------------------------------------------------------- /src/187. Semiprimes/187.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using std::vector; 6 | 7 | static vector gen_primes(long long n); 8 | 9 | int main() { 10 | const long long upper_limit = 100000000LL; 11 | vector primes = gen_primes(upper_limit); 12 | long long count = 0; 13 | for (auto iter = primes.begin(); iter != primes.end(); ++iter) { 14 | long long upper_bound = upper_limit / *iter; 15 | auto upper_iter = std::upper_bound(iter, primes.end(), upper_bound); 16 | if (upper_iter == primes.end()) { 17 | break; 18 | } 19 | count += upper_iter - iter; 20 | } 21 | std::cout << count << std::endl; 22 | } 23 | 24 | static vector gen_primes(long long n) { 25 | // Sieve of Eratosthenes 26 | vector sieve(n + 1); 27 | sieve[0] = false; // so that the index starts from 1 28 | for (long long i = 1; i <= n; ++i) { 29 | if (i % 2 == 0) { 30 | sieve[i] = false; 31 | } else { 32 | sieve[i] = true; 33 | } 34 | } 35 | 36 | sieve[1] = false; // 1 is not prime 37 | sieve[2] = true; // 2 is the only even prime 38 | 39 | long long factor = 3; 40 | while (factor <= int(std::sqrt(n))) { 41 | for (long long i = factor * factor; i < n; i += factor) { 42 | sieve[i] = false; 43 | } 44 | do { 45 | factor += 2; 46 | } while (sieve[factor] == false); 47 | } 48 | 49 | vector primes; 50 | for (long long i = 0; i < sieve.size(); ++i) { 51 | if (sieve[i]) { 52 | primes.push_back(i); 53 | } 54 | } 55 | return primes; 56 | } 57 | -------------------------------------------------------------------------------- /src/187. Semiprimes/187.rb: -------------------------------------------------------------------------------- 1 | require 'prime' 2 | 3 | upper_limit = 10 ** 8 4 | primes = [] 5 | Prime.each(upper_limit / 2) {|p| primes << p} 6 | 7 | count = 0 8 | 0.upto(primes.size - 1) do |i| 9 | j = primes.size - 1 10 | upper_bound = upper_limit / primes[i] 11 | # could be furthur optimized with binary search 12 | j -= 1 while primes[j] > upper_bound 13 | break if j < i 14 | count += j - i + 1 15 | end 16 | puts count 17 | -------------------------------------------------------------------------------- /src/188. The hyperexponentiation of a number/188.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "math/big" 6 | ) 7 | 8 | func main() { 9 | var m big.Int 10 | m.Exp(big.NewInt(10), big.NewInt(8), nil) 11 | fmt.Println(hyperExp(int64(1777), int64(1855), &m)) 12 | } 13 | 14 | func hyperExp(a int64, b int64, m *big.Int) *big.Int { 15 | var result big.Int 16 | if b == 1 { 17 | result.Mod(big.NewInt(a), m) 18 | return &result 19 | } else { 20 | result.Exp(big.NewInt(a), hyperExp(a, b - 1, m), m) 21 | return &result 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/188. The hyperexponentiation of a number/188.java: -------------------------------------------------------------------------------- 1 | import java.math.BigInteger; 2 | 3 | public class Main { 4 | 5 | public static void main(String[] args) { 6 | BigInteger m = BigInteger.valueOf(100_000_000); 7 | System.out.println(hyperExp(1777, 1855, m)); 8 | } 9 | 10 | private static BigInteger hyperExp(long a, long b, BigInteger m) { 11 | if (b == 1) { 12 | return BigInteger.valueOf(a).mod(m); 13 | } else { 14 | return BigInteger.valueOf(a).modPow(hyperExp(a, b - 1, m), m); 15 | } 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /src/188. The hyperexponentiation of a number/188.rb: -------------------------------------------------------------------------------- 1 | def hyper_exp(a, b, m) 2 | if b == 1 3 | a % m 4 | else 5 | a.pow(hyper_exp(a, b - 1, m), m) 6 | end 7 | end 8 | 9 | puts hyper_exp(1777, 1855, 100_000_000) 10 | -------------------------------------------------------------------------------- /src/204. Generalised Hamming Numbers/204.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using std::set; 7 | using std::vector; 8 | 9 | static set gen_hammings(long long upper_limit, int hamming_type); 10 | static set gen_primes(long long n); 11 | 12 | int main() { 13 | const long long upper_limit = 1000000000LL; 14 | set hammings = gen_hammings(upper_limit, 100); 15 | std::cout << hammings.size() << std::endl; 16 | return 0; 17 | } 18 | 19 | static set gen_hammings(long long upper_limit, int hamming_type) { 20 | set primes = gen_primes(hamming_type); 21 | set hammings{1}; 22 | for (auto p : primes) { 23 | set temp(hammings); 24 | for (auto h : hammings) { 25 | while (h * p <= upper_limit) { 26 | temp.insert(h * p); 27 | h *= p; 28 | } 29 | } 30 | hammings = temp; 31 | } 32 | return hammings; 33 | } 34 | 35 | static set gen_primes(long long n) { 36 | // Sieve of Eratosthenes 37 | vector sieve(n + 1); 38 | sieve[0] = false; // so that the index starts from 1 39 | for (long long i = 1; i <= n; ++i) { 40 | if (i % 2 == 0) { 41 | sieve[i] = false; 42 | } else { 43 | sieve[i] = true; 44 | } 45 | } 46 | 47 | sieve[1] = false; // 1 is not prime 48 | sieve[2] = true; // 2 is the only even prime 49 | 50 | long long factor = 3; 51 | while (factor <= int(std::sqrt(n))) { 52 | for (long long i = factor * factor; i < n; i += factor) { 53 | sieve[i] = false; 54 | } 55 | do { 56 | factor += 2; 57 | } while (sieve[factor] == false); 58 | } 59 | 60 | set primes; 61 | for (long long i = 0; i < sieve.size(); ++i) { 62 | if (sieve[i]) { 63 | primes.insert(i); 64 | } 65 | } 66 | return primes; 67 | } 68 | -------------------------------------------------------------------------------- /src/204. Generalised Hamming Numbers/204.java: -------------------------------------------------------------------------------- 1 | import java.util.TreeSet; 2 | 3 | public class Main { 4 | 5 | public static void main(String[] args) { 6 | final long upperLimit = 1_000_000_000; 7 | TreeSet hammings = genHammings(upperLimit, 100); 8 | System.out.println(hammings.size()); 9 | } 10 | 11 | private static TreeSet genHammings(long upperLimit, int hamingType) { 12 | TreeSet primes = genPrimes(hamingType); 13 | TreeSet hammings = new TreeSet<>(); 14 | hammings.add(1L); 15 | for (long p : primes) { 16 | TreeSet temp = new TreeSet<>(hammings); 17 | for (long h : hammings) { 18 | while (h * p <= upperLimit) { 19 | temp.add(h * p); 20 | h *= p; 21 | } 22 | } 23 | hammings = temp; 24 | } 25 | return hammings; 26 | } 27 | 28 | private static TreeSet genPrimes(int n) { 29 | // Sieve of Eratosthenes 30 | boolean[] sieve = new boolean[n + 1]; 31 | sieve[0] = false; // so that the index starts from 1 32 | for (int i = 1; i <= n; ++i) { 33 | if (i % 2 == 0) { 34 | sieve[i] = false; 35 | } else { 36 | sieve[i] = true; 37 | } 38 | } 39 | 40 | sieve[1] = false; // 1 is not prime 41 | sieve[2] = true; // 2 is the only even prime 42 | 43 | int factor = 3; 44 | while (factor <= Math.sqrt(n)) { 45 | for (int i = factor * factor; i < n; i += factor) { 46 | sieve[i] = false; 47 | } 48 | do { 49 | factor += 2; 50 | } while (!sieve[factor]); 51 | } 52 | 53 | TreeSet primes = new TreeSet<>(); 54 | for (int i = 0; i < sieve.length; ++i) { 55 | if (sieve[i]) { 56 | primes.add(i); 57 | } 58 | } 59 | return primes; 60 | } 61 | 62 | } 63 | -------------------------------------------------------------------------------- /src/205. Dice Game/205.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import( 4 | "fmt" 5 | "math" 6 | "math/big" 7 | ) 8 | 9 | func main() { 10 | pyramidal := roll([]int{1, 2, 3, 4}, 9) 11 | cubic := roll([]int{1, 2, 3, 4, 5, 6}, 6) 12 | 13 | pyramidal_pr := make(map[int]big.Rat) 14 | for k, v := range pyramidal { 15 | pyramidal_pr[k] = *big.NewRat(int64(v), int64(math.Pow(4, 9))) 16 | } 17 | 18 | cubic_pr := make(map[int]big.Rat) 19 | for k, v := range cubic { 20 | cubic_pr[k] = *big.NewRat(int64(v), int64(math.Pow(6, 6))) 21 | } 22 | 23 | var beats_pr big.Rat 24 | for p, p_pr := range pyramidal_pr { 25 | for c, c_pr := range cubic_pr { 26 | if p > c { 27 | var pc_pr big.Rat 28 | pc_pr.Mul(&p_pr, &c_pr) 29 | beats_pr.Add(&beats_pr, &pc_pr) 30 | } 31 | } 32 | } 33 | fmt.Println(beats_pr.FloatString(7)) 34 | } 35 | 36 | func roll(dices []int, times int) map[int]int { 37 | counter := make(map[int]int) 38 | for _, d := range dices { 39 | counter[d] = 1 40 | } 41 | for t := 1; t <= times - 1; t++ { 42 | acc := make(map[int]int) 43 | for k, v := range counter { 44 | for _, d := range dices { 45 | acc[k + d] += v 46 | } 47 | } 48 | counter = acc 49 | } 50 | return counter 51 | } 52 | -------------------------------------------------------------------------------- /src/205. Dice Game/205.py: -------------------------------------------------------------------------------- 1 | from fractions import Fraction 2 | 3 | def roll(dices, times): 4 | counter = {} 5 | for d in dices: 6 | counter[d] = 1 7 | for t in range(1, times): 8 | acc = {} 9 | for k, v in counter.items(): 10 | for d in dices: 11 | acc[k + d] = acc.get(k + d, 0) + v 12 | counter = acc 13 | return counter 14 | 15 | pyramidal = roll([1, 2, 3, 4], 9) 16 | cubic = roll([1, 2, 3, 4, 5, 6], 6) 17 | 18 | pyramidal_pr = {} 19 | for k, v in pyramidal.items(): 20 | pyramidal_pr[k] = Fraction(v, 4 ** 9) 21 | 22 | cubic_pr = {} 23 | for k, v in cubic.items(): 24 | cubic_pr[k] = Fraction(v, 6 ** 6) 25 | 26 | beats_pr = 0 27 | for p, p_pr in pyramidal_pr.items(): 28 | for c, c_pr in cubic_pr.items(): 29 | if p > c: 30 | beats_pr += p_pr * c_pr 31 | 32 | print("%.7f" % float(beats_pr)) 33 | -------------------------------------------------------------------------------- /src/205. Dice Game/205.rb: -------------------------------------------------------------------------------- 1 | def roll(dices, times) 2 | counter = {} 3 | dices.each do |d| 4 | counter[d] = 1 5 | end 6 | (times - 1).times do |t| 7 | acc = Hash.new(0) 8 | counter.each do |k, v| 9 | dices.each do |d| 10 | acc[k + d] += v 11 | end 12 | end 13 | counter = acc 14 | end 15 | counter 16 | end 17 | 18 | pyramidal = roll((1..4).to_a, 9) 19 | cubic = roll((1..6).to_a, 6) 20 | 21 | pyramidal_pr = {} 22 | pyramidal.each do |k, v| 23 | pyramidal_pr[k] = v.quo(4 ** 9) 24 | end 25 | 26 | cubic_pr = {} 27 | cubic.each do |k, v| 28 | cubic_pr[k] = v.quo(6 ** 6) 29 | end 30 | 31 | beats_pr = 0 32 | pyramidal_pr.each do |p, p_pr| 33 | cubic_pr.each do |c, c_cr| 34 | beats_pr += p_pr * c_cr if p > c 35 | end 36 | end 37 | printf('%.7f', beats_pr.to_f) 38 | -------------------------------------------------------------------------------- /src/206. Concealed Square/206.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "math" 6 | "regexp" 7 | "strconv" 8 | ) 9 | 10 | func main() { 11 | r, _ := regexp.Compile("1\\d2\\d3\\d4\\d5\\d6\\d7\\d8\\d9") 12 | for i := int64(math.Sqrt(10203040506070809)); i < int64(math.Sqrt(19293949596979899)); i++ { 13 | if i % 10 == 3 || i % 10 == 7 { 14 | s := strconv.FormatInt(i * i, 10) 15 | m := r.MatchString(s) 16 | if m { 17 | fmt.Println(i * 10) 18 | break 19 | } 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/206. Concealed Square/206.java: -------------------------------------------------------------------------------- 1 | import java.util.regex.Matcher; 2 | import java.util.regex.Pattern; 3 | 4 | public class Main { 5 | 6 | public static void main(String[] args) { 7 | 8 | Pattern r = Pattern.compile("1\\d2\\d3\\d4\\d5\\d6\\d7\\d8\\d9"); 9 | for (long n = (long) Math.sqrt(10203040506070809.0); n < (long) Math.sqrt(19293949596979899.0); n++) { 10 | if (n % 10 == 3 || n % 10 == 7) { 11 | // note that n^2 is within the range of 64-bit integer, i.e, long 12 | String s = Long.toString(n * n); 13 | Matcher m = r.matcher(s); 14 | if (m.find()) { 15 | System.out.println(n * 10); 16 | break; 17 | } 18 | } 19 | } 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/206. Concealed Square/206.lua: -------------------------------------------------------------------------------- 1 | -- only works for Lua 5.3+, needs 64 bit integer support 2 | for num = math.floor(math.sqrt(10203040506070809)), 3 | math.floor(math.sqrt(19293949596979899)) do 4 | if num % 10 == 3 or num % 10 == 7 then 5 | num_square = string.format("%d", num * num) 6 | if num_square:match("1%d2%d3%d4%d5%d6%d7%d8%d9") then 7 | print(num * 10) 8 | break 9 | end 10 | end 11 | end 12 | -------------------------------------------------------------------------------- /src/206. Concealed Square/206.py: -------------------------------------------------------------------------------- 1 | import math 2 | import re 3 | 4 | for num in range(int(math.sqrt(10203040506070809)), int(math.sqrt(19293949596979899))): 5 | if num % 10 == 3 or num % 10 == 7: 6 | if re.match(r"1\d2\d3\d4\d5\d6\d7\d8\d9", str(num * num)): 7 | print(num * 10) 8 | break 9 | -------------------------------------------------------------------------------- /src/206. Concealed Square/206.rb: -------------------------------------------------------------------------------- 1 | Math.sqrt(10203040506070809).to_i.upto(Math.sqrt(19293949596979899).to_i) do |num| 2 | if num % 10 == 3 or num % 10 == 7 3 | if (num * num).to_s =~ /1\d2\d3\d4\d5\d6\d7\d8\d9/ 4 | puts num * 10 5 | break 6 | end 7 | end 8 | end -------------------------------------------------------------------------------- /src/301. Nim/301.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int nim_win(uint32_t n); 5 | 6 | int main(void) { 7 | int count = 0; 8 | for (uint32_t n = 1; n <= 1U << 30; ++n) { 9 | if (nim_win(n)) { 10 | ++count; 11 | } 12 | } 13 | printf("%d\n", count); 14 | return 0; 15 | } 16 | 17 | // https://en.wikipedia.org/wiki/Nim#Mathematical_theory 18 | int nim_win(uint32_t n) { 19 | return (n ^ (n * 2) ^ (n * 3)) == 0; 20 | } 21 | -------------------------------------------------------------------------------- /src/301. Nim/301.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | bool nim_win(uint32_t n); 5 | 6 | int main(void) { 7 | int count = 0; 8 | for (uint32_t n = 1; n <= 1U << 30; ++n) { 9 | if (nim_win(n)) { 10 | ++count; 11 | } 12 | } 13 | std::cout << count << std::endl; 14 | return 0; 15 | } 16 | 17 | // https://en.wikipedia.org/wiki/Nim#Mathematical_theory 18 | bool nim_win(uint32_t n) { 19 | return (n ^ (n * 2) ^ (n * 3)) == 0; 20 | } 21 | -------------------------------------------------------------------------------- /src/301. Nim/301.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | count := 0 7 | for n := uint32(1); n <= uint32(1) << 30; n++ { 8 | if nimWin(n) { 9 | count++ 10 | } 11 | } 12 | fmt.Println(count) 13 | } 14 | 15 | // https://en.wikipedia.org/wiki/Nim#Mathematical_theory 16 | func nimWin(n uint32) bool { 17 | return n ^ (n * 2) ^ (n * 3) == 0 18 | } 19 | -------------------------------------------------------------------------------- /src/301. Nim/301.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | public static void main(String[] args) { 3 | int count = 0; 4 | for (int n = 1; n <= 1 << 30; ++n) { 5 | if (nimWin(n)) { 6 | ++count; 7 | } 8 | } 9 | System.out.println(count); 10 | } 11 | 12 | // https://en.wikipedia.org/wiki/Nim#Mathematical_theory 13 | private static boolean nimWin(int n) { 14 | return (n ^ (n * 2) ^ (n * 3)) == 0; 15 | } 16 | } -------------------------------------------------------------------------------- /src/301. Nim/301.lua: -------------------------------------------------------------------------------- 1 | -- https://en.wikipedia.org/wiki/Nim#Mathematical_theory 2 | function nim_win(n) 3 | return n ~ n * 2 ~ n * 3 == 0 4 | end 5 | 6 | count = 0 7 | for n = 1, 1 << 30 do 8 | if nim_win(n) then 9 | count = count + 1 10 | end 11 | end 12 | print(count) 13 | -------------------------------------------------------------------------------- /src/346. Strong Repunits/346.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | upper_limit = 10 ** 12 4 | 5 | # calculates rep units with digits more than 3 6 | # any number n > 2 is a rep units 11 in base n - 1 7 | rep_units = set() 8 | for b in range(2, int(math.sqrt(upper_limit))): 9 | r = b + 1 10 | while True: 11 | r = r * b + 1 12 | if r > upper_limit: 13 | break 14 | rep_units.add(r) 15 | 16 | # https://en.wikipedia.org/wiki/Goormaghtigh_conjecture#Application_to_repunits 17 | # 31 (111 in base 5, 11111 in base 2) and 8191 (111 in base 90, 1111111111111 in base 2) 18 | # are the only two numbers that are repunits with at least 3 digits in two different bases. 19 | if upper_limit >= 1: 20 | rep_units.add(1) 21 | if upper_limit >= 31: 22 | rep_units.add(31) 23 | if upper_limit >= 8191: 24 | rep_units.add(8191) 25 | print(sum(rep_units)) 26 | -------------------------------------------------------------------------------- /src/346. Strong Repunits/346.rb: -------------------------------------------------------------------------------- 1 | require 'set' 2 | 3 | upper_limit = 10 ** 12 4 | 5 | # calculates rep units with digits more than 3 6 | # any number n > 2 is a rep units 11 in base n - 1 7 | rep_units = Set.new 8 | 2.upto(Math.sqrt(upper_limit)) do |b| 9 | r = b + 1 10 | loop do 11 | r = r * b + 1 12 | break if r > upper_limit 13 | rep_units << r 14 | end 15 | end 16 | # https://en.wikipedia.org/wiki/Goormaghtigh_conjecture#Application_to_repunits 17 | # 31 (111 in base 5, 11111 in base 2) and 8191 (111 in base 90, 1111111111111 in base 2) 18 | # are the only two numbers that are repunits with at least 3 digits in two different bases. 19 | rep_units << 1 if upper_limit >= 1 20 | rep_units << 31 if upper_limit >= 31 21 | rep_units << 8191 if upper_limit >= 8191 22 | puts rep_units.inject(:+) -------------------------------------------------------------------------------- /src/348. Sum of a square and a cube/348.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | using std::map; 11 | using std::set; 12 | using std::string; 13 | using std::vector; 14 | 15 | static bool is_palindrome(long long n); 16 | 17 | int main() { 18 | // if the result is not enough, take a bigger guess 19 | long long upper_limit = 1000000000LL; 20 | 21 | set squares; 22 | for (long long a = 2; a < std::sqrt(upper_limit); ++a) { 23 | squares.insert(a * a); 24 | } 25 | 26 | set cubes; 27 | for (long long b = 2; b * b * b < upper_limit; ++b) { 28 | cubes.insert(b * b * b); 29 | } 30 | 31 | map candidates; 32 | for (long long s : squares) { 33 | for (long long c : cubes) { 34 | if (is_palindrome(s + c)) { 35 | ++candidates[s + c]; 36 | } 37 | } 38 | } 39 | 40 | vector result; 41 | for (auto kv : candidates) { 42 | if (kv.second == 4) { 43 | result.push_back(kv.first); 44 | } 45 | } 46 | 47 | if (result.size() >= 5) { 48 | std::sort(result.begin(), result.end()); 49 | std::cout << std::accumulate(result.begin(), result.begin() + 5, 0); 50 | } 51 | } 52 | 53 | static bool is_palindrome(long long n) { 54 | string original = std::to_string(n); 55 | string reversed(original.rbegin(), original.rend()); 56 | return original == reversed; 57 | } 58 | -------------------------------------------------------------------------------- /src/348. Sum of a square and a cube/348.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.HashMap; 3 | import java.util.HashSet; 4 | import java.util.List; 5 | import java.util.Map; 6 | import java.util.Set; 7 | 8 | public class Main { 9 | 10 | private static final long UPPER_LIMIT = 1_000_000_000L; 11 | 12 | public static void main(String[] args) { 13 | // if the result is not enough, take a bigger guess 14 | 15 | Set squares = new HashSet<>(); 16 | for (long a = 2; a < Math.sqrt(UPPER_LIMIT); a++) { 17 | squares.add(a * a); 18 | } 19 | 20 | Set cubes = new HashSet<>(); 21 | for (long b = 2; b * b * b < UPPER_LIMIT; b++) { 22 | cubes.add(b * b * b); 23 | } 24 | 25 | Map candidates = new HashMap<>(); 26 | for (long s : squares) { 27 | for (long c : cubes) { 28 | if (isPalindrome(s + c)) { 29 | int count = candidates.getOrDefault(s + c, 0); 30 | candidates.put(s + c, count + 1); 31 | } 32 | } 33 | } 34 | 35 | List result = new ArrayList<>(); 36 | for (Map.Entry kv : candidates.entrySet()) { 37 | if (kv.getValue() == 4) { 38 | result.add(kv.getKey()); 39 | } 40 | } 41 | 42 | if (result.size() >= 5) { 43 | result.sort(Long::compareTo); 44 | long sum = result.stream() 45 | .mapToLong(Long::longValue) 46 | .limit(5) 47 | .sum(); 48 | System.out.println(sum); 49 | } 50 | } 51 | 52 | private static boolean isPalindrome(long n) { 53 | String original = Long.toString(n); 54 | return reverseString(original).equals(original); 55 | } 56 | 57 | private static String reverseString(String original) { 58 | return new StringBuilder(original).reverse().toString(); 59 | } 60 | 61 | } 62 | -------------------------------------------------------------------------------- /src/348. Sum of a square and a cube/348.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | def is_palindrome(n): 4 | return str(n) == str(n)[::-1] 5 | 6 | # if the result is not enough, take a bigger guess 7 | upper_limit = 10 ** 9 8 | 9 | squares = [] 10 | for a in range(2, int(math.sqrt(upper_limit))): 11 | squares.append(a * a) 12 | 13 | cubes = [] 14 | b = 2 15 | while b * b * b < upper_limit: 16 | cubes.append(b * b * b) 17 | b += 1 18 | 19 | candidates = {} 20 | for s in squares: 21 | for c in cubes: 22 | if is_palindrome(s + c): 23 | count = candidates.get(s + c, 0) 24 | candidates[s + c] = count + 1 25 | 26 | result = [] 27 | for k, v in candidates.items(): 28 | if v == 4: 29 | result.append(k) 30 | 31 | if len(result) >= 5: 32 | result.sort() 33 | print(sum(result[0:5])) 34 | -------------------------------------------------------------------------------- /src/348. Sum of a square and a cube/348.rb: -------------------------------------------------------------------------------- 1 | class Integer 2 | def is_palindrome? 3 | self.to_s == self.to_s.reverse 4 | end 5 | end 6 | 7 | # if the result is not enough, take a bigger guess 8 | upper_limit = 10 ** 9 9 | 10 | squares = [] 11 | 2.upto(Math.sqrt(upper_limit)) do |a| 12 | squares << a * a 13 | end 14 | 15 | cubes = [] 16 | b = 2 17 | while b * b * b < upper_limit 18 | cubes << b * b * b 19 | b += 1 20 | end 21 | 22 | candidates = Hash.new(0) 23 | squares.each do |s| 24 | cubes.each do |c| 25 | candidates[s + c] += 1 if (s + c).is_palindrome? 26 | end 27 | end 28 | 29 | candidates.keep_if {|k, v| v == 4} 30 | if candidates.size >= 5 31 | puts candidates.keys.min(5).inject(:+) 32 | end 33 | -------------------------------------------------------------------------------- /src/357. Prime generating integers/357.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using std::vector; 6 | 7 | static vector gen_primes(long long n); 8 | 9 | int main() { 10 | const long long upper_limit = 100000000LL; 11 | vector primes = gen_primes(upper_limit); 12 | 13 | vector prime_gens(upper_limit + 1, true); 14 | for (long long d = 1; d <= upper_limit; ++d) { 15 | for (long long k = d; k <= upper_limit / d; ++k) { 16 | if (k + d > upper_limit) { 17 | break; 18 | } 19 | if (!primes[k + d]) { 20 | prime_gens[k * d] = false; 21 | } 22 | } 23 | } 24 | 25 | long long sum = 0; 26 | for (long long i = 0; i < prime_gens.size(); ++i) { 27 | if (prime_gens[i]) { 28 | sum += i; 29 | } 30 | } 31 | std::cout << sum << std::endl; 32 | return 0; 33 | } 34 | 35 | static vector gen_primes(long long n) { 36 | // Sieve of Eratosthenes 37 | vector sieve(n + 1); 38 | sieve[0] = false; // so that the index starts from 1 39 | for (long long i = 1; i <= n; ++i) { 40 | if (i % 2 == 0) { 41 | sieve[i] = false; 42 | } else { 43 | sieve[i] = true; 44 | } 45 | } 46 | 47 | sieve[1] = false; // 1 is not prime 48 | sieve[2] = true; // 2 is the only even prime 49 | 50 | long long factor = 3; 51 | while (factor <= int(std::sqrt(n))) { 52 | for (long long i = factor * factor; i < n; i += factor) { 53 | sieve[i] = false; 54 | } 55 | do { 56 | factor += 2; 57 | } while (sieve[factor] == false); 58 | } 59 | 60 | return sieve; 61 | } 62 | -------------------------------------------------------------------------------- /src/357. Prime generating integers/357.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "math" 6 | ) 7 | 8 | func main() { 9 | const upper_limit = 100000000 10 | primes := genPrimes(upper_limit) 11 | 12 | primeGens := make([]bool, upper_limit + 1) 13 | for i := range primeGens { 14 | primeGens[i] = true 15 | } 16 | 17 | for d := 1; d <= upper_limit; d++ { 18 | for k := d; k <= upper_limit / d; k++ { 19 | if k + d > upper_limit { 20 | break 21 | } 22 | if !primes[k + d] { 23 | primeGens[k * d] = false 24 | } 25 | } 26 | } 27 | 28 | sum := 0 29 | for i, v := range primeGens { 30 | if v { 31 | sum += i 32 | } 33 | } 34 | fmt.Println(sum) 35 | } 36 | 37 | func genPrimes(n int) []bool { 38 | // Sieve of Eratosthenes 39 | sieve := make([]bool, n + 1) 40 | sieve[0] = false // so that the index starts from 1 41 | for i := 1; i < n; i++ { 42 | if i % 2 == 0 { 43 | sieve[i] = false 44 | } else { 45 | sieve[i] = true 46 | } 47 | } 48 | sieve[1] = false // 1 is not prime 49 | sieve[2] = true // 2 is the only even prime 50 | 51 | factor := 3 52 | for factor <= int(math.Sqrt(float64(n))) { 53 | for i := factor * factor; i < n; i += factor { 54 | sieve[i] = false 55 | } 56 | factor += 2 57 | for sieve[factor] == false { 58 | factor += 2 59 | } 60 | } 61 | return sieve 62 | } 63 | -------------------------------------------------------------------------------- /src/357. Prime generating integers/357.rb: -------------------------------------------------------------------------------- 1 | require 'prime' 2 | 3 | upper_limit = 100_000_000 4 | primes = Array.new(upper_limit + 1, false) 5 | Prime.each(upper_limit) {|p| primes[p] = true} 6 | 7 | prime_gens = Array.new(upper_limit + 1, true) 8 | 1.upto(upper_limit) do |d| 9 | d.upto(upper_limit / d) do |k| 10 | break if d + k > upper_limit 11 | if prime_gens[d * k] and not primes[d + k] 12 | prime_gens[d * k] = false 13 | end 14 | end 15 | end 16 | 17 | sum = 0 18 | prime_gens.each_with_index do |n, i| 19 | sum += i if n 20 | end 21 | puts sum 22 | -------------------------------------------------------------------------------- /src/387. Harshad Numbers/387.rb: -------------------------------------------------------------------------------- 1 | require 'prime' 2 | 3 | class Integer 4 | def sum_digits 5 | self.to_s.chars.map(&:to_i).inject(:+) 6 | end 7 | 8 | def harshad? 9 | d = self.sum_digits 10 | self % d == 0 11 | end 12 | 13 | # assumes that it's already tested a Harshad 14 | def strong? 15 | d = self.sum_digits 16 | (self / d).prime? 17 | end 18 | end 19 | 20 | right_truncatable_harshads = [] 21 | right_truncatable_harshads[0] = (1 .. 9).to_a 22 | prime_right_truncatable_harshads = [] 23 | 1.upto(13) do |i| 24 | right_truncatable_harshads[i] = [] 25 | right_truncatable_harshads[i - 1].each do |h| 26 | is_h_strong = h.strong? 27 | 0.upto(9) do |d| 28 | n = h * 10 + d 29 | if n.harshad? 30 | right_truncatable_harshads[i] << n 31 | end 32 | if is_h_strong and n.prime? 33 | prime_right_truncatable_harshads << n 34 | end 35 | end 36 | end 37 | end 38 | 39 | puts prime_right_truncatable_harshads.inject(:+) 40 | -------------------------------------------------------------------------------- /src/504. Square on the Inside/504.rb: -------------------------------------------------------------------------------- 1 | require 'set' 2 | 3 | m = 100 4 | 5 | def tri_key(x, y) 6 | x, y = y, x if x > y 7 | x << 8 | y 8 | end 9 | 10 | $gcd = {} 11 | 1.upto(m) do |x| 12 | x.upto(m) do |y| 13 | $gcd[tri_key(x, y)] = x.gcd(y) 14 | end 15 | end 16 | 17 | def gcd(x, y) 18 | $gcd[tri_key(x, y)] 19 | end 20 | 21 | $tri_cache = {} 22 | # https://en.wikipedia.org/wiki/Pick%27s_theorem 23 | def tri(x, y) 24 | k = tri_key(x, y) 25 | v = $tri_cache[k] 26 | return v if v != nil 27 | points = ((x - 1) * (y - 1) - gcd(x, y) + 1) / 2 28 | $tri_cache[k] = points 29 | points 30 | end 31 | 32 | def quad_key(a, b, c, d) 33 | key_arr = tri_key(a, b), tri_key(b, c), tri_key(c, d), tri_key(d, a) 34 | key_arr.sort! 35 | key_arr.join('_').to_sym 36 | end 37 | 38 | def lattice_count(a, b, c, d) 39 | tri(a, b) + tri(b, c) + tri(c, d) + tri(d, a) + a + b + c + d - 3 40 | end 41 | 42 | $squares = Set.new 43 | 1.upto(m * 2) do |p| 44 | $squares << p * p 45 | end 46 | 47 | count = 0 48 | 1.upto(m) do |a| 49 | 1.upto(m) do |b| 50 | a.upto(m) do |c| 51 | b.upto(m) do |d| 52 | if $squares.include? lattice_count(a, b, c, d) 53 | count += 1 54 | count += 1 unless a == c 55 | count += 1 unless b == d 56 | count += 1 unless a == c or b == d 57 | end 58 | end 59 | end 60 | end 61 | end 62 | 63 | puts count 64 | -------------------------------------------------------------------------------- /src/587. Concave triangle/587.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | double concave_triangle_area(int n); 5 | 6 | const double PI = 3.141592653589793238462643383279502884; 7 | 8 | int main() { 9 | // assume that the radius of the circle is 1 10 | double l_section_area = 1 - PI / 4; 11 | int n = 2; 12 | while (1) { 13 | if (concave_triangle_area(n) / l_section_area < 0.001) { 14 | printf("%d", n); 15 | break; 16 | } 17 | ++n; 18 | } 19 | } 20 | 21 | double concave_triangle_area(int n) { 22 | // assume the height of the concave triangle is h 23 | // solve the equation 24 | // (1 - n*h)^2 + (1 - h)^2 = 1 25 | double h = (n + 1 - sqrt(2 * n)) / (n * n + 1); 26 | double radius_angle = acos((1 - h) / 1); 27 | double circular_sector_area = radius_angle / 2; 28 | double inner_upper_triangle_area = (sqrt(1 - (1 - h) * (1 - h))) * (1 - 1.0 / n) / 2; 29 | double containing_triangle_area = 1.0 * (1.0 / n) / 2; 30 | return containing_triangle_area + inner_upper_triangle_area - circular_sector_area; 31 | } 32 | -------------------------------------------------------------------------------- /src/587. Concave triangle/587.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | double concave_triangle_area(int n); 5 | 6 | const double PI = 3.141592653589793238462643383279502884; 7 | 8 | int main() { 9 | // assume that the radius of the circle is 1 10 | double l_section_area = 1 - PI / 4; 11 | int n = 2; 12 | while (true) { 13 | if (concave_triangle_area(n) / l_section_area < 0.001) { 14 | std::cout << n << std::endl; 15 | break; 16 | } 17 | ++n; 18 | } 19 | } 20 | 21 | double concave_triangle_area(int n) { 22 | // assume the height of the concave triangle is h 23 | // solve the equation 24 | // (1 - n*h)^2 + (1 - h)^2 = 1 25 | double h = (n + 1 - std::sqrt(2 * n)) / (n * n + 1); 26 | double radius_angle = std::acos((1 - h) / 1); 27 | double circular_sector_area = radius_angle / 2; 28 | double inner_upper_triangle_area = (std::sqrt(1 - (1 - h) * (1 - h))) * (1 - 1.0 / n) / 2; 29 | double containing_triangle_area = 1.0 * (1.0 / n) / 2; 30 | return containing_triangle_area + inner_upper_triangle_area - circular_sector_area; 31 | } 32 | -------------------------------------------------------------------------------- /src/587. Concave triangle/587.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "math" 6 | ) 7 | 8 | func main() { 9 | // assume that the radius of the circle is 1 10 | lSectionArea := 1 - math.Pi / 4 11 | n := 2.0 12 | for { 13 | if concaveTriangleArea(n) / lSectionArea < 0.001 { 14 | fmt.Println(n) 15 | break 16 | } 17 | n += 1 18 | } 19 | } 20 | 21 | func concaveTriangleArea(n float64) float64 { 22 | // assume the height of the concave triangle is h 23 | // solve the equation 24 | // (1 - n*h)^2 + (1 - h)^2 = 1 25 | h := (n + 1 - math.Sqrt(2 * n)) / (n * n + 1) 26 | radiusAngle := math.Acos((1 - h) / 1) 27 | circularSectorArea := radiusAngle / 2 28 | innerUpperTriangleArea := (math.Sqrt(1 - (1 - h) * (1 - h))) * (1 - 1.0 / n) / 2 29 | containingTriangleArea := 1.0 * (1.0 / n) / 2 30 | return containingTriangleArea + innerUpperTriangleArea - circularSectorArea 31 | } 32 | -------------------------------------------------------------------------------- /src/587. Concave triangle/587.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | 3 | public static void main(String[] args) { 4 | // assume that the radius of the circle is 1 5 | double lSectionArea = 1 - Math.PI / 4; 6 | int n = 2; 7 | while(true) { 8 | if (concaveTriangleArea(n) / lSectionArea < 0.001) { 9 | System.out.println(n); 10 | break; 11 | } 12 | n++; 13 | } 14 | } 15 | 16 | private static double concaveTriangleArea(int n) { 17 | // assume the height of the concave triangle is h 18 | // solve the equation 19 | // (1 - n*h)^2 + (1 - h)^2 = 1 20 | double h = (n + 1 - Math.sqrt(2 * n)) / (n * n + 1); 21 | double radiusAngle = Math.acos((1 - h) / 1); 22 | double circularSectorArea = radiusAngle / 2; 23 | double innerUpperTriangleArea = (Math.sqrt(1 - (1 - h) * (1 - h))) * (1 - 1.0 / n) / 2; 24 | double containingTriangleArea = 1.0 * (1.0 / n) / 2; 25 | return containingTriangleArea + innerUpperTriangleArea - circularSectorArea; 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/622. Riffle Shuffles/622.rb: -------------------------------------------------------------------------------- 1 | require 'prime' 2 | 3 | # https://en.wikipedia.org/wiki/Out_shuffle 4 | # The number of out shuffles required to return a deck of cards of even size, N, 5 | # to its original order is given by the multiplicative order of 2 modulo (N − 1). 6 | 7 | shuffle_num = 60 8 | 9 | all_factors = [1] 10 | (2 ** shuffle_num - 1).prime_division.each do |pe| 11 | p, e = pe[0], pe[1] 12 | new_factors = [] 13 | all_factors.each do |f| 14 | 1.upto(e) do |m| 15 | new_factors << f * (p ** m) 16 | end 17 | end 18 | all_factors += new_factors 19 | end 20 | 21 | # https://en.wikipedia.org/wiki/Multiplicative_order 22 | # In number theory, given an integer a and a positive integer n with gcd(a,n) = 1, 23 | # the multiplicative order of a modulo n is the smallest positive integer k with 24 | # a^k = 1 mod n 25 | 26 | # we know that 2^k mod n = 1, but k might not be the smallest value 27 | def verify_ord(n, k) 28 | 1.upto(k - 1) do |e| 29 | return false if 2 ** e % n == 1 30 | end 31 | true 32 | end 33 | 34 | sum = 0 35 | all_factors.each do |f| 36 | next if f == 1 37 | if verify_ord(f, shuffle_num) 38 | sum += f + 1 39 | end 40 | end 41 | puts sum 42 | --------------------------------------------------------------------------------