├── .gitignore ├── Atoi_Implementation └── main.go ├── Backspace_String_Compare └── main.go ├── Best_Time_To_Sell_Stock └── main.go ├── Contiguous_Array └── main.go ├── Counting_Elements └── main.go ├── Course_Schedule_II └── main.go ├── Coursera_Last_Digit └── main.go ├── Depth_First_Search └── main.go ├── Diameter_Binary_Tree └── main.go ├── Group_Anagrams └── main.go ├── Kadane_Algorithm └── main.go ├── LFU_Cache ├── .main.go.swp └── main.go ├── LICENSE ├── LRU_Cache └── main.go ├── Last_Stone_Weight └── main.go ├── Linked_List_Cycle_2 └── main.go ├── Linked_List_Middle └── main.go ├── Longest_Palindrome_Substring └── main.go ├── Longest_Substring_Non_Repeating_Chars └── main.go ├── Min_Stack └── main.go ├── Move_Element_To_End └── main.go ├── Palindrome_Number └── main.go ├── Problem_10_Euler └── main.go ├── Problem_11_Euler ├── input.txt └── main.go ├── Problem_12_Euler └── main.go ├── Problem_13_Euler ├── input.txt └── main.go ├── Problem_14_Euler └── main.go ├── Problem_15_Euler └── main.go ├── Problem_16_Euler └── main.go ├── Problem_17_Euler └── main.go ├── Problem_18_Euler ├── input.txt └── main.go ├── Problem_19_Euler └── main.go ├── Problem_1_Euler └── main.go ├── Problem_20_Euler └── main.go ├── Problem_21_Euler └── main.go ├── Problem_22_Euler ├── input.txt └── main.go ├── Problem_23_Euler └── main.go ├── Problem_24_Euler └── main.go ├── Problem_25_Euler ├── .tool-versions ├── differences-10.000000.png ├── differences-100.000000.png ├── differences-1000.000000.png ├── differences-10000.000000.png ├── differences-100000.000000.png ├── differences-1000000.000000.png ├── differences-35.000000.png ├── differences-40.000000.png ├── differences-50.000000.png ├── differences-5000.000000.png ├── functions-10.000000.png ├── functions-100.000000.png ├── functions-1000.000000.png ├── functions-10000.000000.png ├── functions-100000.000000.png ├── functions-1000000.000000.png ├── functions-1500.000000.png ├── functions-35.000000.png ├── functions-40.000000.png ├── functions-45.000000.png ├── functions-50.000000.png ├── functions-500.000000.png ├── functions-5000.000000.png ├── functions-5000000000.000000.png ├── functions-60.000000.png └── main.go ├── Problem_26_Euler └── main.go ├── Problem_27_Euler ├── main.go └── result.txt ├── Problem_28_Euler └── main.go ├── Problem_29_Euler ├── main.go ├── main.py └── test ├── Problem_2_Euler └── main.go ├── Problem_30_Euler └── main.go ├── Problem_31_Euler └── main.go ├── Problem_32_Euler └── main.go ├── Problem_33_Euler └── main.go ├── Problem_34_Euler └── main.go ├── Problem_35_Euler └── main.go ├── Problem_36_Euler └── main.go ├── Problem_37_Euler └── main.go ├── Problem_38_Euler └── main.go ├── Problem_39_Euler └── main.go ├── Problem_3_Euler └── main.go ├── Problem_40_Euler └── main.go ├── Problem_41_Euler └── main.go ├── Problem_42_Euler ├── main.go └── words.txt ├── Problem_43_Euler └── main.go ├── Problem_44_Euler └── main.go ├── Problem_45_Euler └── main.go ├── Problem_46_Euler └── main.go ├── Problem_47_Euler └── main.go ├── Problem_48_Euler └── main.go ├── Problem_49_Euler └── main.go ├── Problem_4_Euler └── main.go ├── Problem_50_Euler └── main.go ├── Problem_51_Euler └── main.go ├── Problem_52_Euler └── main.go ├── Problem_53_Euler └── main.go ├── Problem_54_Euler ├── main.go └── poker.txt ├── Problem_55_Euler └── main.go ├── Problem_56_Euler └── main.go ├── Problem_57_Euler └── main.go ├── Problem_58_Euler └── main.go ├── Problem_59_Euler ├── 0059_cipher.txt └── main.go ├── Problem_5_Euler └── main.go ├── Problem_60_Euler └── main.go ├── Problem_61_Euler └── main.go ├── Problem_62_Euler └── main.go ├── Problem_63_Euler └── main.go ├── Problem_64_Euler └── main.go ├── Problem_65_Euler └── main.go ├── Problem_66_Euler ├── main.go └── main.py ├── Problem_67_Euler ├── 0067_triangle.txt └── main.go ├── Problem_68_Euler └── main.go ├── Problem_69_Euler └── main.go ├── Problem_6_Euler └── main.go ├── Problem_70_Euler └── main.go ├── Problem_71_Euler └── main.go ├── Problem_72_Euler └── main.go ├── Problem_73_Euler └── main.go ├── Problem_74_Euler ├── main.go └── main_test.go ├── Problem_75_Euler └── main.go ├── Problem_76_Euler └── main.go ├── Problem_77_Euler └── main.go ├── Problem_78_Euler └── main.go ├── Problem_79_Euler ├── 0079_keylog.txt └── main.go ├── Problem_7_Euler └── main.go ├── Problem_80_Euler ├── main.go └── main.py ├── Problem_81_Euler ├── 0081_matrix.txt └── main.go ├── Problem_8_Euler ├── main.go └── number.txt ├── Problem_9_Euler └── main.go ├── Product_Of_Array_Except_Itself └── main.go ├── README.md ├── Regular_Expression_Matching ├── main.c └── main.go ├── Single_Cycle_Check └── main.go ├── Smallest_Difference └── main.go ├── Subets └── main.py ├── Three_Number_Sum └── main.go ├── Two_City_Scheduling └── main.py ├── Word_Ladder_II ├── .main.go.swp └── main.go ├── Zigzag_Conversion ├── main.go └── main.py ├── go.mod └── go.sum /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.exe~ 4 | *.dll 5 | *.so 6 | *.dylib 7 | 8 | # Test binary, built with `go test -c` 9 | *.test 10 | 11 | # Output of the go coverage tool, specifically when used with LiteIDE 12 | *.out 13 | 14 | # Dependency directories (remove the comment below to include it) 15 | # vendor/ 16 | .idea -------------------------------------------------------------------------------- /Atoi_Implementation/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | // https://leetcode.com/problems/string-to-integer-atoi/ 4 | 5 | import ( 6 | "math" 7 | "strconv" 8 | "strings" 9 | ) 10 | 11 | func myAtoi(str string) int { 12 | str = strings.TrimLeft(str, " ") 13 | str = strings.Split(str, " ")[0] 14 | str = strings.Split(str, ".")[0] 15 | elem := []string{} 16 | for idx, val := range str { 17 | if idx == 0 && strings.ContainsAny(string(val), "-+") { 18 | elem = append(elem, string(val)) 19 | continue 20 | } 21 | if _, err := strconv.Atoi(string(val)); err == nil { 22 | elem = append(elem, string(val)) 23 | } else { 24 | break 25 | } 26 | } 27 | str = strings.Join(elem, "") 28 | val, err := strconv.ParseInt(str, 10, 64) 29 | if val < 0 && val < math.MinInt32 { 30 | return math.MinInt32 31 | } else if val > math.MaxInt32 { 32 | return math.MaxInt32 33 | } 34 | if err == nil { 35 | return int(val) 36 | } 37 | return 0 38 | } 39 | -------------------------------------------------------------------------------- /Backspace_String_Compare/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | // https://leetcode.com/explore/featured/card/30-day-leetcoding-challenge/529/week-2/3291/ 4 | 5 | import ( 6 | "fmt" 7 | "strings" 8 | ) 9 | 10 | func formatString(S string) string { 11 | s := []string{} 12 | for _, v := range S { 13 | n := len(s) - 1 14 | if string(v) == "#" { 15 | if n >= 0 { 16 | s = s[:n] 17 | } 18 | } else { 19 | s = append(s, string(v)) 20 | } 21 | } 22 | return strings.Join(s, "") 23 | } 24 | 25 | func backspaceCompare(S string, T string) bool { 26 | return formatString(S) == formatString(T) 27 | } 28 | -------------------------------------------------------------------------------- /Best_Time_To_Sell_Stock/main.go: -------------------------------------------------------------------------------- 1 | package maxProfit 2 | 3 | // https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/ 4 | 5 | func maxProfit(prices []int) int { 6 | profit := 0 7 | for idx, _ := range prices { 8 | if idx+1 < len(prices) && prices[idx+1] > prices[idx] { 9 | profit += prices[idx+1] - prices[idx] 10 | } 11 | } 12 | 13 | return profit 14 | } 15 | -------------------------------------------------------------------------------- /Contiguous_Array/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | // https://leetcode.com/problems/contiguous-array 4 | 5 | func max(a int, b int) int { 6 | if a > b { 7 | return a 8 | } 9 | return b 10 | } 11 | 12 | func findMaxLength(nums []int) int { 13 | max_len, sum := 0, 0 14 | count := map[int]int{} 15 | count[0] = -1 16 | for idx, val := range nums { 17 | adder := 1 18 | if val == 0 { 19 | adder = -1 20 | } 21 | sum += adder 22 | if elem, ok := count[sum]; ok { 23 | max_len = max(max_len, idx-elem) 24 | } else { 25 | count[sum] = idx 26 | } 27 | } 28 | 29 | return max_len 30 | } 31 | -------------------------------------------------------------------------------- /Counting_Elements/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | // https://leetcode.com/explore/featured/card/30-day-leetcoding-challenge/528/week-1/3289/ 4 | 5 | import ( 6 | "fmt" 7 | "sort" 8 | ) 9 | 10 | func max(a int, b int) int { 11 | if a > b { 12 | return a 13 | } 14 | return b 15 | } 16 | 17 | func countElements(arr []int) int { 18 | setElem := map[int]int{} 19 | count := 0 20 | temp := 0 21 | for _, val := range arr { 22 | if _, ok := setElem[val]; !ok { 23 | setElem[val] = 0 24 | } 25 | setElem[val] += 1 26 | } 27 | 28 | keys := []int{} 29 | for k, _ := range setElem { 30 | keys = append(keys, k) 31 | } 32 | sort.Ints(keys) 33 | 34 | for _, val := range keys { 35 | if _, ok := setElem[val+1]; ok { 36 | temp += setElem[val] 37 | } else { 38 | count += temp 39 | temp = 0 40 | } 41 | } 42 | return count 43 | } 44 | -------------------------------------------------------------------------------- /Course_Schedule_II/main.go: -------------------------------------------------------------------------------- 1 | type set map[int]map[int]bool 2 | type counter map[int]int 3 | 4 | func findOrder(numCourses int, prerequisites [][]int) []int { 5 | courses := set{} 6 | degrees := counter{} 7 | result := []int{} 8 | if len(prerequisites) == 0{ 9 | for i := numCourses - 1; i >= 0; i -- { 10 | result = append(result, i) 11 | } 12 | return result 13 | } 14 | for i := 0; i < numCourses; i++ { 15 | degrees[i] = 0 16 | if _, ok := courses[i]; !ok { 17 | courses[i] = make(map[int]bool) 18 | } 19 | } 20 | for _, course := range prerequisites { 21 | dep := course[1] 22 | preq := course[0] 23 | if _, ok := courses[preq][dep]; ok { 24 | return []int{} 25 | } 26 | courses[dep][preq] = true 27 | degrees[preq] += 1 28 | } 29 | queue := make([]int, 0) 30 | for c, degree := range degrees { 31 | if degree == 0 { 32 | queue = append(queue, c) 33 | } 34 | } 35 | for len(queue) > 0 { 36 | course := queue[0] 37 | queue = queue[1:] 38 | result = append(result, course) 39 | for c := range courses[course] { 40 | degrees[c] -= 1 41 | if degrees[c] == 0 { 42 | queue = append(queue, c) 43 | } 44 | } 45 | } 46 | if len(result) != len(degrees) { 47 | return []int{} 48 | } 49 | return result 50 | } 51 | -------------------------------------------------------------------------------- /Coursera_Last_Digit/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "math" 6 | ) 7 | 8 | func BinetFormula(n float64) int64 { 9 | sqrt5 := math.Sqrt(5) 10 | phi := (1 + sqrt5) / 2 11 | ans := math.Round(math.Pow(phi, n) / sqrt5) 12 | fmt.Printf("Value at n: %f in fibonnaci sequence is: %f\n", n, ans) 13 | return int64(ans) 14 | } 15 | 16 | func LastDigit(n float64) int64 { 17 | var seqMax int64 = 60 18 | var count int64 = 2 19 | var val int64 = 0 20 | 21 | fibSequence := make([]int64, seqMax) 22 | fibSequence[count] = 0 23 | fibSequence[1] = 1 24 | for count < seqMax { 25 | fibSequence[count] = fibSequence[count-1] + fibSequence[count-2] 26 | count += 1 27 | } 28 | 29 | count = 0 30 | for count <= int64(n) % 60{ 31 | val += fibSequence[count] 32 | count += 1 33 | } 34 | 35 | return val % 10 36 | } 37 | 38 | 39 | func main(){ 40 | fmt.Println(LastDigit(3)) 41 | } -------------------------------------------------------------------------------- /Depth_First_Search/main.go: -------------------------------------------------------------------------------- 1 | package Depth_First_Search 2 | 3 | 4 | // https://www.algoexpert.io/questions/Depth-first%20Search 5 | 6 | 7 | 8 | // Do not edit the class below except 9 | // for the depthFirstSearch method. 10 | // Feel free to add new properties 11 | // and methods to the class. 12 | type Node struct { 13 | Name string 14 | Children []*Node 15 | } 16 | 17 | 18 | // Optimised Version O(V + E) 19 | // V - Vertex 20 | // E - Edges 21 | func (n *Node) DepthFirstSearch(array []string) []string { 22 | // Write your code here. 23 | array = append(array, n.Name) 24 | for _, node := range n.Children { 25 | array = node.DepthFirstSearch(array) 26 | } 27 | 28 | return array 29 | } 30 | -------------------------------------------------------------------------------- /Diameter_Binary_Tree/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | // https://leetcode.com/explore/featured/card/30-day-leetcoding-challenge/529/week-2/3293/ 6 | 7 | /** 8 | * Definition for a binary tree node. 9 | * type TreeNode struct { 10 | * Val int 11 | * Left *TreeNode 12 | * Right *TreeNode 13 | * } 14 | */ 15 | 16 | func max(a int, b int) int { 17 | if a > b { 18 | return a 19 | } 20 | return b 21 | } 22 | 23 | func treeDepth(root *TreeNode, count *int) int { 24 | if root == nil { 25 | return 0 26 | } 27 | len_left := treeDepth(root.Left, count) 28 | len_right := treeDepth(root.Right, count) 29 | fmt.Println(len_left, len_right, *count) 30 | *count = max(len_left+len_right+1, *count) 31 | return max(len_left, len_right) + 1 32 | } 33 | 34 | func diameterOfBinaryTree(root *TreeNode) int { 35 | count := 1 36 | if root == nil { 37 | return 0 38 | } 39 | treeDepth(root, &count) 40 | return count - 1 41 | } 42 | -------------------------------------------------------------------------------- /Group_Anagrams/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | // https://leetcode.com/explore/featured/card/30-day-leetcoding-challenge/528/week-1/3288/ 4 | 5 | import ( 6 | "sort" 7 | "strings" 8 | ) 9 | 10 | func sortString(w string) string { 11 | s := strings.Split(w, "") 12 | sort.Strings(s) 13 | return strings.Join(s, "") 14 | } 15 | 16 | func groupAnagrams(strs []string) [][]string { 17 | content := map[string][]string{} 18 | output := [][]string{} 19 | for _, str := range strs { 20 | idx := sortString(str) 21 | content[idx] = append(content[idx], str) 22 | } 23 | 24 | for _, v := range content { 25 | output = append(output, v) 26 | } 27 | return output 28 | } 29 | -------------------------------------------------------------------------------- /Kadane_Algorithm/main.go: -------------------------------------------------------------------------------- 1 | package Kadane_Algorithm 2 | 3 | 4 | //algoexpert.io/questions/Kadane's%20Algorithm 5 | 6 | func max(a int, b int) int{ 7 | if a > b { 8 | return a 9 | } 10 | return b 11 | } 12 | 13 | // Optimised version 14 | // O(n) time 15 | // O(1) space 16 | func KadanesAlgorithm(array []int) int { 17 | max_curr, max_at_idx := array[0], array[0] 18 | for idx := 1; idx < len(array); idx++{ 19 | el := array[idx] 20 | max_at_idx = max(el, max_at_idx + el) 21 | max_curr = max(max_curr, max_at_idx) 22 | } 23 | return max_curr 24 | } 25 | -------------------------------------------------------------------------------- /LFU_Cache/.main.go.swp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tiemma/algorithm-solutions/b259be686f62302d12f508eb798d5444bfdd3b37/LFU_Cache/.main.go.swp -------------------------------------------------------------------------------- /LFU_Cache/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | // https://leetcode.com/problems/lfu-cache/ 4 | 5 | import ( 6 | "container/list" 7 | "math" 8 | ) 9 | 10 | type LFUCache struct { 11 | store map[int]int 12 | capacity int 13 | 14 | order *list.List 15 | order_map map[int]*list.Element 16 | 17 | count map[int][2]int // 0 - key count, 1 - overall count for the cache 18 | curr_idx int 19 | max_count int 20 | } 21 | 22 | func Constructor(capacity int) LFUCache { 23 | if capacity <= 0 { 24 | return LFUCache{} 25 | } 26 | store := make(map[int]int, capacity) 27 | count := make(map[int][2]int, capacity) 28 | count[0] = [2]int{math.MaxInt64, math.MaxInt64} 29 | 30 | order := list.New() 31 | order_map := make(map[int]*list.Element, capacity) 32 | 33 | return LFUCache{store: store, capacity: capacity, order: order, order_map: order_map, count: count} 34 | } 35 | 36 | func (this *LFUCache) SetCURRIdx() { 37 | for k, val := range this.count { 38 | if val[0] < this.count[this.curr_idx][0] { 39 | this.curr_idx = k 40 | } else if val[0] == this.count[this.curr_idx][0] { 41 | if val[1] < this.count[this.curr_idx][1] { 42 | this.curr_idx = k 43 | } 44 | } 45 | } 46 | } 47 | 48 | func (this *LFUCache) SetLRUEntry(key int) { 49 | this.max_count += 1 50 | this.count[key] = [2]int{this.count[key][0] + 1, this.max_count} 51 | } 52 | 53 | func (this *LFUCache) Get(key int) int { 54 | if this.capacity == 0 { 55 | return -1 56 | } 57 | if elem, ok := this.order_map[key]; ok { 58 | this.SetLRUEntry(key) 59 | this.order.MoveToBack(elem) 60 | return this.store[key] 61 | } 62 | return -1 63 | } 64 | 65 | func (this *LFUCache) Put(key int, value int) { 66 | if this.capacity <= 0 { 67 | return 68 | } 69 | if len(this.order_map) == this.capacity { 70 | if _, ok := this.store[key]; !ok { 71 | this.SetCURRIdx() 72 | temp := this.order.Remove(this.order_map[this.curr_idx]) 73 | delete(this.store, temp.(int)) 74 | delete(this.order_map, temp.(int)) 75 | delete(this.count, temp.(int)) 76 | this.curr_idx = 0 77 | } 78 | } 79 | 80 | if val, ok := this.order_map[key]; ok { 81 | this.order.MoveToBack(val) 82 | } else { 83 | this.order_map[key] = this.order.PushFront(key) 84 | this.count[key] = [2]int{-1, this.max_count} 85 | } 86 | this.SetLRUEntry(key) 87 | this.store[key] = value 88 | } 89 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Bakare Emmanuel Oluwatimilehin 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 | -------------------------------------------------------------------------------- /LRU_Cache/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | // 4 | 5 | // Inefficient 6 | // O(N) time and space 7 | 8 | import ( 9 | "container/list" 10 | ) 11 | 12 | // Efficient 13 | // O(1) time and space 14 | 15 | type LRUCache struct { 16 | store map[int]int 17 | capacity int 18 | order *list.List 19 | order_map map[int]*list.Element 20 | } 21 | 22 | func Constructor(capacity int) LRUCache { 23 | store := make(map[int]int, capacity) 24 | order := list.New() 25 | order_map := make(map[int]*list.Element, capacity) 26 | return LRUCache{store: store, capacity: capacity, order: order, order_map: order_map} 27 | } 28 | 29 | func (this *LRUCache) Get(key int) int { 30 | if elem, ok := this.order_map[key]; ok { 31 | this.order.MoveToFront(elem) 32 | return this.store[key] 33 | } 34 | return -1 35 | } 36 | 37 | func (this *LRUCache) Put(key int, value int) { 38 | if len(this.order_map) == this.capacity { 39 | if _, ok := this.store[key]; !ok { 40 | temp := this.order.Remove(this.order.Back()) 41 | delete(this.store, temp.(int)) 42 | delete(this.order_map, temp.(int)) 43 | } 44 | 45 | } 46 | this.store[key] = value 47 | if val, ok := this.order_map[key]; ok { 48 | this.order.MoveToFront(val) 49 | } else { 50 | this.order_map[key] = this.order.PushFront(key) 51 | } 52 | 53 | } 54 | -------------------------------------------------------------------------------- /Last_Stone_Weight/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | // https://leetcode.com/problems/last-stone-weight/ 4 | 5 | import "container/heap" 6 | 7 | type IntHeap []int 8 | 9 | func (h IntHeap) Len() int { return len(h) } 10 | func (h IntHeap) Less(i, j int) bool { return h[i] > h[j] } 11 | func (h IntHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } 12 | 13 | func (h *IntHeap) Push(x interface{}) { 14 | *h = append(*h, x.(int)) 15 | } 16 | 17 | func (h *IntHeap) Pop() interface{} { 18 | old := *h 19 | n := len(old) 20 | x := old[n-1] 21 | *h = old[0 : n-1] 22 | return x 23 | } 24 | 25 | func lastStoneWeight(stones []int) int { 26 | 27 | h := &IntHeap{} 28 | for _, val := range stones { 29 | *h = append(*h, val) 30 | } 31 | heap.Init(h) 32 | for h.Len() > 1 { 33 | a, b := heap.Pop(h), heap.Pop(h) 34 | if a == b { 35 | // heap.Push(h, a.(int)) 36 | continue 37 | } 38 | heap.Push(h, a.(int)-b.(int)) 39 | } 40 | if h.Len() == 0 { 41 | return 0 42 | } 43 | return heap.Pop(h).(int) 44 | } 45 | -------------------------------------------------------------------------------- /Linked_List_Cycle_2/main.go: -------------------------------------------------------------------------------- 1 | package Linked_List_Cycle_2 2 | 3 | /** 4 | * Definition for singly-linked list. 5 | * type ListNode struct { 6 | * Val int 7 | * Next *ListNode 8 | * } 9 | */ 10 | 11 | import "fmt" 12 | 13 | func moveNode(head *ListNode) (bool, *ListNode) { 14 | if head.Next != nil { 15 | head = head.Next 16 | return true, head 17 | } 18 | return false, head 19 | } 20 | 21 | func getNodeAtIndex(head *ListNode, n int) *ListNode { 22 | for i := 0; i < n; i++ { 23 | head = head.Next 24 | } 25 | return head 26 | } 27 | 28 | func detectCycle(head *ListNode) *ListNode { 29 | one_step := head 30 | two_step := head 31 | 32 | end_two := false 33 | end_one := false 34 | 35 | count := 0 36 | 37 | for one_step != nil && two_step != nil{ 38 | fmt.Println(count) 39 | fmt.Printf("node_1 %d == node_2 %d\n", one_step.Val, two_step.Val) 40 | 41 | end_one, one_step = moveNode(one_step) 42 | end_two, two_step = moveNode(two_step) 43 | end_two, two_step = moveNode(two_step) 44 | 45 | fmt.Printf("node_1 %d == node_2 %d\n\n", one_step.Val, two_step.Val) 46 | 47 | 48 | if two_step == one_step { 49 | if end_two == false || end_one == false { 50 | return nil 51 | } 52 | 53 | return getNodeAtIndex(head, count) 54 | } 55 | 56 | count += 1 57 | 58 | } 59 | 60 | return nil 61 | } -------------------------------------------------------------------------------- /Linked_List_Middle/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | // https://leetcode.com/explore/featured/card/30-day-leetcoding-challenge/529/week-2/3290/ 4 | 5 | /** 6 | * Definition for singly-linked list. 7 | * type ListNode struct { 8 | * Val int 9 | * Next *ListNode 10 | * } 11 | */ 12 | func middleNode(head *ListNode) *ListNode { 13 | prev_head := head 14 | end := false 15 | for { 16 | if head == nil { 17 | return prev_head 18 | } 19 | if head.Next != nil { 20 | head = head.Next.Next 21 | } else { 22 | end = true 23 | } 24 | if end { 25 | return prev_head 26 | } 27 | prev_head = prev_head.Next 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Longest_Palindrome_Substring/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | // https://leetcode.com/problems/longest-palindromic-substring/ 4 | 5 | import ( 6 | "strings" 7 | ) 8 | 9 | func oddifyString(s string) []string { 10 | val := []string{} 11 | for _, s := range s { 12 | val = append(val, "#") 13 | val = append(val, string(s)) 14 | } 15 | val = append(val, "#") 16 | return val 17 | } 18 | 19 | func min(a int, b int) int { 20 | if a < b { 21 | return a 22 | } 23 | return b 24 | } 25 | 26 | func longestPalindrome(sb string) string { 27 | s := oddifyString(sb) 28 | N := len(s) 29 | res := []string{} 30 | if N == 0 { 31 | return "" 32 | } 33 | p := make([]int, N) 34 | c := 0 35 | r := 0 36 | max := 0 37 | for i := 0; i < N; i++ { 38 | mirror := (2 * c) - i 39 | if i < r { 40 | p[i] = min(r-i, p[mirror]) 41 | } 42 | 43 | a := i + (1 + p[i]) 44 | b := i - (1 + p[i]) 45 | 46 | for a < N && b >= 0 && s[a] == s[b] { 47 | p[i]++ 48 | a++ 49 | b-- 50 | } 51 | 52 | if i+p[i] > r { 53 | c = i 54 | r = i + p[i] 55 | 56 | if p[i] > max { 57 | max = p[i] 58 | res = s[i-p[i] : r+1] 59 | } 60 | } 61 | } 62 | return strings.ReplaceAll(strings.Join(res, ""), "#", "") 63 | } 64 | -------------------------------------------------------------------------------- /Longest_Substring_Non_Repeating_Chars/main.go: -------------------------------------------------------------------------------- 1 | func find(arr []string, v string) (bool, int) { 2 | for idx, str := range arr{ 3 | if v == str{ 4 | return true, idx 5 | } 6 | } 7 | return false, -1 8 | } 9 | 10 | func lengthOfLongestSubstring(s string) int { 11 | ans := 0 12 | result := []string{} 13 | 14 | for _, v := range s{ 15 | found, idx := find(result, string(v)) 16 | if found { 17 | result = result[idx+1:] 18 | } 19 | result = append(result, string(v)) 20 | if ans < len(result) { 21 | ans = len(result) 22 | : } 23 | 24 | } 25 | return ans 26 | } 27 | -------------------------------------------------------------------------------- /Min_Stack/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "math" 5 | ) 6 | 7 | type MinStack struct { 8 | stack []int 9 | size int 10 | } 11 | 12 | /** initialize your data structure here. */ 13 | func Constructor() MinStack { 14 | return MinStack{} 15 | } 16 | 17 | func (this *MinStack) Push(x int) { 18 | this.stack = append(this.stack, x) 19 | this.size += 1 20 | } 21 | 22 | func (this *MinStack) Pop() { 23 | if this.size > 0 { 24 | this.size -= 1 25 | this.stack = this.stack[:this.size] 26 | } 27 | } 28 | 29 | func (this *MinStack) Top() int { 30 | return this.stack[this.size-1] 31 | } 32 | 33 | func (this *MinStack) GetMin() int { 34 | min := math.MaxInt64 35 | for _, elem := range this.stack { 36 | if elem < min { 37 | min = elem 38 | } 39 | } 40 | return min 41 | } 42 | 43 | /** 44 | * Your MinStack object will be instantiated and called as such: 45 | * obj := Constructor(); 46 | * obj.Push(x); 47 | * obj.Pop(); 48 | * param_3 := obj.Top(); 49 | * param_4 := obj.GetMin(); 50 | */ 51 | -------------------------------------------------------------------------------- /Move_Element_To_End/main.go: -------------------------------------------------------------------------------- 1 | package Move_Element_To_End 2 | 3 | 4 | // https://www.algoexpert.io/questions/Move%20Element%20To%20End 5 | 6 | 7 | // Optimised version O(n) 8 | func MoveElementToEnd(array []int, toMove int) []int { 9 | lastIdx := 0 10 | for idx := 1; idx < len(array); idx++{ 11 | if(array[lastIdx] == toMove && array[idx] != toMove){ 12 | array[idx], array[lastIdx] = array[lastIdx], array[idx] 13 | lastIdx += 1 14 | } else if(array[lastIdx] != toMove){ 15 | lastIdx += 1 16 | } 17 | } 18 | return array 19 | } 20 | -------------------------------------------------------------------------------- /Palindrome_Number/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | // https://leetcode.com/problems/palindrome-number/ 4 | 5 | import ( 6 | "strconv" 7 | "strings" 8 | ) 9 | 10 | func Reverse(s string) string { 11 | elem := []string{} 12 | for i := len(s) - 1; i >= 0; i-- { 13 | elem = append(elem, string(s[i])) 14 | } 15 | return strings.Join(elem, "") 16 | } 17 | 18 | func isPalindrome(x int) bool { 19 | if x < 0 { 20 | return false 21 | } 22 | 23 | strNum := strconv.Itoa(x) 24 | if strNum == Reverse(strNum) { 25 | return true 26 | } 27 | return false 28 | } 29 | -------------------------------------------------------------------------------- /Problem_10_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | 4 | // https://projecteuler.net/problem=10 5 | 6 | import ( 7 | "flag" 8 | "fmt" 9 | "math" 10 | ) 11 | 12 | 13 | func isPrime(n int) bool{ 14 | i := 2 15 | for i <= int(math.Sqrt(float64(n))) { 16 | if n % i == 0 { 17 | return false 18 | } 19 | i++ 20 | } 21 | return true 22 | } 23 | 24 | func sumOfPrimeToNBF(n int) int{ 25 | i := 2 26 | sum := 0 27 | for i < n { 28 | if isPrime(i){ 29 | sum += i 30 | } 31 | i++ 32 | } 33 | return sum 34 | } 35 | 36 | func main(){ 37 | maxNumPtr := flag.Int("number", 2_000_000, "Integer for the max range") 38 | flag.Parse() 39 | fmt.Println("Prime sum to n is ", sumOfPrimeToNBF(*maxNumPtr)) 40 | } 41 | 42 | 43 | -------------------------------------------------------------------------------- /Problem_11_Euler/input.txt: -------------------------------------------------------------------------------- 1 | 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 | -------------------------------------------------------------------------------- /Problem_11_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | 4 | // https://projecteuler.net/problem=11 5 | 6 | import ( 7 | "bufio" 8 | "flag" 9 | "fmt" 10 | "math" 11 | "os" 12 | "strconv" 13 | "strings" 14 | ) 15 | 16 | 17 | func upperDiagonal(arr [20][20]int, row int, col int, grid int, window int) int { 18 | j := 0 19 | product := 1 20 | if row <= grid - window && col >= window - 1 { 21 | for j < window { 22 | product *= arr[row+j][col-j] 23 | j += 1 24 | } 25 | } 26 | fmt.Println(row, col, product) 27 | return product 28 | } 29 | 30 | 31 | 32 | func lowerDiagonal(arr [20][20]int, row int, col int, grid int, window int) int { 33 | j := 0 34 | product := 1 35 | if row <= grid - window && col <= grid - window { 36 | for j < window { 37 | product *= arr[row+j][col+j] 38 | j += 1 39 | } 40 | } 41 | return product 42 | } 43 | 44 | func up(arr [20][20]int, row int, col int, grid int, window int) int { 45 | j := 0 46 | product := 1 47 | if row >= window - 1 { 48 | for j < window { 49 | product *= arr[row-j][col] 50 | j += 1 51 | } 52 | } 53 | return product 54 | } 55 | 56 | func down(arr [20][20]int, row int, col int, grid int, window int) int { 57 | j := 0 58 | product := 1 59 | if row <= grid - window { 60 | for j < window { 61 | product *= arr[row+j][col] 62 | j += 1 63 | } 64 | } 65 | return product 66 | } 67 | 68 | func left(arr [20][20]int, row int, col int, grid int, window int) int { 69 | j := 0 70 | product := 1 71 | if col >= window - 1 { 72 | for j < window { 73 | product *= arr[row][col-j] 74 | j += 1 75 | } 76 | } 77 | return product 78 | } 79 | 80 | func right(arr [20][20]int, row int, col int, grid int, window int) int { 81 | j := 0 82 | product := 1 83 | if col <= grid - window { 84 | for j < window { 85 | product *= arr[row][col+j] 86 | j += 1 87 | } 88 | } 89 | return product 90 | } 91 | 92 | 93 | 94 | func setMaxProduct(product int, temp int) int{ 95 | if temp > product { 96 | product = temp 97 | } 98 | return product 99 | } 100 | 101 | func maxDiagonalProduct(arr [20][20]int, window int, grid int) int{ 102 | i := 0 103 | product := math.MinInt64 104 | for i < int(len(arr) * len(arr[0])) { 105 | row, col := i / grid, i % grid 106 | product = setMaxProduct(product, down(arr, row, col, grid, window)) 107 | product = setMaxProduct(product, up(arr, row, col, grid, window)) 108 | product = setMaxProduct(product, right(arr, row, col, grid, window)) 109 | product = setMaxProduct(product, lowerDiagonal(arr, row, col, grid, window)) 110 | product = setMaxProduct(product, upperDiagonal(arr, row, col, grid, window)) 111 | product = setMaxProduct(product, left(arr, row, col, grid, window)) 112 | i += 1 113 | } 114 | return product 115 | } 116 | 117 | 118 | func main(){ 119 | 120 | fileName := flag.String("file", "input.txt", "File to read integers from") 121 | window := flag.Int("window", 4, "Window along the diagonal to multiply") 122 | flag.Parse() 123 | 124 | input, err := os.Open(*fileName) 125 | if err != nil { 126 | panic(err) 127 | } 128 | defer input.Close() 129 | 130 | buffer := bufio.NewScanner(input) 131 | stringArr := []string{} 132 | grid := 20 133 | numArr := [20][20]int{} 134 | for buffer.Scan(){ 135 | stringArr = strings.Split(buffer.Text(), " ") 136 | for idx, el := range stringArr { 137 | numArr[idx/grid][idx%grid], err = strconv.Atoi(el) 138 | } 139 | } 140 | fmt.Println(maxDiagonalProduct(numArr, *window, grid)) 141 | } 142 | 143 | -------------------------------------------------------------------------------- /Problem_12_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | 4 | // https://projecteuler.net/problem=12 5 | 6 | import ( 7 | "flag" 8 | "fmt" 9 | "math" 10 | ) 11 | 12 | type Maps map[int]map[int]int 13 | 14 | // The triangle number sum is a simple AP sum 15 | func getTriangleNumber(n int) int { 16 | return n * (n + 1) / 2 17 | } 18 | 19 | 20 | // Every single natural number is a mutiple of a prime 21 | // So we can decompose that product with a simple prime factor check 22 | // And reduce the powers till we get another prime 23 | func countMultiples(n int, divisorMap Maps) map[int]int { 24 | i := 2 25 | factorMap := map[int]int{} 26 | temp := n 27 | 28 | for i <= int(math.Sqrt(float64(n))) { 29 | for n % i == 0 && n > 1 { 30 | n = n /i 31 | 32 | if val, ok := factorMap[i]; !ok{ 33 | factorMap[i] = 1 34 | } else { 35 | factorMap[i] = val + 1 36 | } 37 | 38 | if _, ok := divisorMap[n]; ok { 39 | fmt.Println("Found value for number ", n, " in divisor map for ", temp) 40 | for key, val := range divisorMap[n] { 41 | if _, ok := factorMap[key]; !ok { 42 | factorMap[key] = val 43 | } else { 44 | factorMap[key] += val 45 | } 46 | } 47 | return factorMap 48 | } 49 | 50 | } 51 | i++ 52 | } 53 | 54 | if n > 1 { 55 | factorMap[n] = 1 56 | 57 | } 58 | 59 | return factorMap 60 | } 61 | 62 | 63 | func highestDivisibleTriangularNumber(maxDivisor int) int{ 64 | divisorMap := Maps{} 65 | n := 2 66 | for n > 0{ 67 | temp := getTriangleNumber(n) 68 | divisorMap[temp] = countMultiples(temp, divisorMap) 69 | // The number of factor compositions is a product of the order of each prime 70 | product := 1 71 | for _,v := range divisorMap[temp]{ 72 | product *= (v + 1) 73 | } 74 | if product >= maxDivisor{ 75 | return temp 76 | } 77 | n += 1 78 | } 79 | return 1 80 | } 81 | 82 | 83 | func main(){ 84 | //divisorMap := Maps{15: {3: 1, 5: 1}} 85 | divisor := flag.Int("divisor", 500, "Flag to indicate the number of divisors to look out for") 86 | flag.Parse() 87 | //fmt.Println("Number of multiples to ", *divisor, " is ", countMultiples(*divisor, divisorMap)) 88 | fmt.Println("Number of multiples to ", *divisor, " is ", highestDivisibleTriangularNumber(*divisor)) 89 | } 90 | 91 | 92 | -------------------------------------------------------------------------------- /Problem_13_Euler/input.txt: -------------------------------------------------------------------------------- 1 | 37107287533902102798797998220837590246510135740250 2 | 46376937677490009712648124896970078050417018260538 3 | 74324986199524741059474233309513058123726617309629 4 | 91942213363574161572522430563301811072406154908250 5 | 23067588207539346171171980310421047513778063246676 6 | 89261670696623633820136378418383684178734361726757 7 | 28112879812849979408065481931592621691275889832738 8 | 44274228917432520321923589422876796487670272189318 9 | 47451445736001306439091167216856844588711603153276 10 | 70386486105843025439939619828917593665686757934951 11 | 62176457141856560629502157223196586755079324193331 12 | 64906352462741904929101432445813822663347944758178 13 | 92575867718337217661963751590579239728245598838407 14 | 58203565325359399008402633568948830189458628227828 15 | 80181199384826282014278194139940567587151170094390 16 | 35398664372827112653829987240784473053190104293586 17 | 86515506006295864861532075273371959191420517255829 18 | 71693888707715466499115593487603532921714970056938 19 | 54370070576826684624621495650076471787294438377604 20 | 53282654108756828443191190634694037855217779295145 21 | 36123272525000296071075082563815656710885258350721 22 | 45876576172410976447339110607218265236877223636045 23 | 17423706905851860660448207621209813287860733969412 24 | 81142660418086830619328460811191061556940512689692 25 | 51934325451728388641918047049293215058642563049483 26 | 62467221648435076201727918039944693004732956340691 27 | 15732444386908125794514089057706229429197107928209 28 | 55037687525678773091862540744969844508330393682126 29 | 18336384825330154686196124348767681297534375946515 30 | 80386287592878490201521685554828717201219257766954 31 | 78182833757993103614740356856449095527097864797581 32 | 16726320100436897842553539920931837441497806860984 33 | 48403098129077791799088218795327364475675590848030 34 | 87086987551392711854517078544161852424320693150332 35 | 59959406895756536782107074926966537676326235447210 36 | 69793950679652694742597709739166693763042633987085 37 | 41052684708299085211399427365734116182760315001271 38 | 65378607361501080857009149939512557028198746004375 39 | 35829035317434717326932123578154982629742552737307 40 | 94953759765105305946966067683156574377167401875275 41 | 88902802571733229619176668713819931811048770190271 42 | 25267680276078003013678680992525463401061632866526 43 | 36270218540497705585629946580636237993140746255962 44 | 24074486908231174977792365466257246923322810917141 45 | 91430288197103288597806669760892938638285025333403 46 | 34413065578016127815921815005561868836468420090470 47 | 23053081172816430487623791969842487255036638784583 48 | 11487696932154902810424020138335124462181441773470 49 | 63783299490636259666498587618221225225512486764533 50 | 67720186971698544312419572409913959008952310058822 51 | 95548255300263520781532296796249481641953868218774 52 | 76085327132285723110424803456124867697064507995236 53 | 37774242535411291684276865538926205024910326572967 54 | 23701913275725675285653248258265463092207058596522 55 | 29798860272258331913126375147341994889534765745501 56 | 18495701454879288984856827726077713721403798879715 57 | 38298203783031473527721580348144513491373226651381 58 | 34829543829199918180278916522431027392251122869539 59 | 40957953066405232632538044100059654939159879593635 60 | 29746152185502371307642255121183693803580388584903 61 | 41698116222072977186158236678424689157993532961922 62 | 62467957194401269043877107275048102390895523597457 63 | 23189706772547915061505504953922979530901129967519 64 | 86188088225875314529584099251203829009407770775672 65 | 11306739708304724483816533873502340845647058077308 66 | 82959174767140363198008187129011875491310547126581 67 | 97623331044818386269515456334926366572897563400500 68 | 42846280183517070527831839425882145521227251250327 69 | 55121603546981200581762165212827652751691296897789 70 | 32238195734329339946437501907836945765883352399886 71 | 75506164965184775180738168837861091527357929701337 72 | 62177842752192623401942399639168044983993173312731 73 | 32924185707147349566916674687634660915035914677504 74 | 99518671430235219628894890102423325116913619626622 75 | 73267460800591547471830798392868535206946944540724 76 | 76841822524674417161514036427982273348055556214818 77 | 97142617910342598647204516893989422179826088076852 78 | 87783646182799346313767754307809363333018982642090 79 | 10848802521674670883215120185883543223812876952786 80 | 71329612474782464538636993009049310363619763878039 81 | 62184073572399794223406235393808339651327408011116 82 | 66627891981488087797941876876144230030984490851411 83 | 60661826293682836764744779239180335110989069790714 84 | 85786944089552990653640447425576083659976645795096 85 | 66024396409905389607120198219976047599490197230297 86 | 64913982680032973156037120041377903785566085089252 87 | 16730939319872750275468906903707539413042652315011 88 | 94809377245048795150954100921645863754710598436791 89 | 78639167021187492431995700641917969777599028300699 90 | 15368713711936614952811305876380278410754449733078 91 | 40789923115535562561142322423255033685442488917353 92 | 44889911501440648020369068063960672322193204149535 93 | 41503128880339536053299340368006977710650566631954 94 | 81234880673210146739058568557934581403627822703280 95 | 82616570773948327592232845941706525094512325230608 96 | 22918802058777319719839450180888072429661980811197 97 | 77158542502016545090413245809786882778948721859617 98 | 72107838435069186155435662884062257473692284509516 99 | 20849603980134001723930671666823555245252804609722 100 | 53503534226472524250874054075591789781264330331690 101 | -------------------------------------------------------------------------------- /Problem_13_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | 4 | // https://projecteuler.net/problem=13 5 | import ( 6 | "bufio" 7 | "flag" 8 | "fmt" 9 | "math" 10 | "os" 11 | "strconv" 12 | "strings" 13 | ) 14 | 15 | 16 | func recurseAdd(arr [100][50]int, window int) []int{ 17 | col := len(arr[0]) - 1 18 | result := []int{} 19 | rem := 0 20 | for col >= 0{ 21 | temp := rem 22 | row := 0 23 | fmt.Println(row, " ", col, " ", temp) 24 | for row < len(arr) { 25 | temp += arr[row][col] 26 | row += 1 27 | } 28 | result = append([]int{temp%10}, result...) 29 | fmt.Println(row, " ", col, " ", temp) 30 | rem = temp / 10 31 | fmt.Println(result) 32 | col -= 1 33 | } 34 | 35 | for rem > 0{ 36 | result = append([]int{rem%10}, result...) 37 | rem /= 10 38 | fmt.Println(result) 39 | } 40 | // return result[len(result)-window:] 41 | return result[:window] 42 | } 43 | 44 | 45 | 46 | func main(){ 47 | 48 | fileName := flag.String("file", "input.txt", "File to read integers from") 49 | window := flag.Int("window", 10, "Window of integers to return") 50 | flag.Parse() 51 | 52 | input, err := os.Open(*fileName) 53 | if err != nil { 54 | panic(err) 55 | } 56 | defer input.Close() 57 | 58 | buffer := bufio.NewScanner(input) 59 | stringArr := []string{} 60 | count := 0 61 | numArr := [100][50]int{} 62 | for buffer.Scan(){ 63 | stringArr = strings.Split(buffer.Text(), "") 64 | for idx, el := range stringArr { 65 | numArr[count][idx], err = strconv.Atoi(el) 66 | } 67 | count += 1 68 | } 69 | var val float64 = 0 70 | for idx, el := range recurseAdd(numArr, *window){ 71 | val += float64(el) * math.Pow(10, float64(*window - idx - 1)) 72 | } 73 | fmt.Println("First ", *window, " digits are ", int(val)) 74 | } 75 | 76 | 77 | 78 | -------------------------------------------------------------------------------- /Problem_14_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | // https://projecteuler.net/problem=14 4 | 5 | import ( 6 | "flag" 7 | "fmt" 8 | "math" 9 | ) 10 | 11 | type Map map[int]int 12 | 13 | func getCollatzSequenceCount(n int, countMap Map) int{ 14 | count := 1 15 | for n > 1 { 16 | if val, ok := countMap[n]; ok { 17 | return count + val 18 | } 19 | if n%2 == 1{ 20 | n = 3*n + 1 21 | } else { 22 | n /= 2 23 | } 24 | count += 1 25 | } 26 | return count 27 | } 28 | 29 | func getTermsCount(maxCount int) int{ 30 | count := math.MinInt64 31 | n := 1 32 | result := 0 33 | countMap := Map{} 34 | for n < maxCount{ 35 | temp := getCollatzSequenceCount(n, countMap) 36 | countMap[n] = temp 37 | if count < temp { 38 | count = temp 39 | result = n 40 | } 41 | n += 1 42 | } 43 | return result 44 | } 45 | 46 | 47 | func main(){ 48 | maxTerms := flag.Int("max", 1_000_000, "Max number of terms obtained from the collatz sequence") 49 | flag.Parse() 50 | 51 | fmt.Println("Variable with max iterations is ", getTermsCount(*maxTerms)) 52 | } 53 | -------------------------------------------------------------------------------- /Problem_15_Euler/main.go: -------------------------------------------------------------------------------- 1 | 2 | package main 3 | // https://projecteuler.net/problem=15 4 | import ( 5 | "flag" 6 | "fmt" 7 | "math/big" 8 | ) 9 | 10 | func factorial(x *big.Int) *big.Int { 11 | n := big.NewInt(1) 12 | if x.Cmp(big.NewInt(0)) == 0 { 13 | return n 14 | } 15 | return n.Mul(x, factorial(n.Sub(x, n))) 16 | } 17 | 18 | 19 | func main() { 20 | grid := flag.Int64("grid", 20, "Window of integers to return") 21 | flag.Parse() 22 | 23 | ud := factorial(big.NewInt(*grid * 2)) 24 | ld := factorial(big.NewInt(*grid)) 25 | n := big.NewInt(1) 26 | n.Div(ud, ld) 27 | n.Div(n, ld) 28 | fmt.Println(n) 29 | } 30 | -------------------------------------------------------------------------------- /Problem_16_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | 4 | // https://projecteuler.net/problem=16 5 | 6 | import ( 7 | "flag" 8 | "fmt" 9 | "math/big" 10 | ) 11 | 12 | func main() { 13 | val := flag.Int64("val", 2, "Number to raise the power to") 14 | exp := flag.Int64("exp", 1_000, "Power of the value") 15 | flag.Parse() 16 | 17 | result := big.NewInt(0) 18 | n := big.NewInt(1) 19 | n.Exp(big.NewInt(*val), big.NewInt(*exp), nil) 20 | for n.Cmp(big.NewInt(0)) != 0{ 21 | temp := big.NewInt(0) 22 | n.DivMod(n, big.NewInt(10), temp) 23 | result.Add(result, temp) 24 | } 25 | fmt.Println("Sum is ", result) 26 | } 27 | 28 | 29 | -------------------------------------------------------------------------------- /Problem_17_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | //://projecteuler.net/problem=17 4 | 5 | import ( 6 | "flag" 7 | "fmt" 8 | "math" 9 | "strconv" 10 | "strings" 11 | ) 12 | 13 | 14 | 15 | func getPowerExtensions(number int) (string, bool){ 16 | extensions := map[int]string{} 17 | extensions[2] = "hundred" 18 | extensions[3] = "thousand" 19 | extensions[6] = "million" 20 | extensions[9] = "billion" 21 | 22 | if val, ok := extensions[number]; ok { 23 | return val, true 24 | } 25 | return "", false 26 | } 27 | 28 | func getExtensions(number int) (string, bool){ 29 | extensions := map[int]string{} 30 | extensions[1] = "one" 31 | extensions[2] = "two" 32 | extensions[3] = "three" 33 | extensions[4] = "four" 34 | extensions[5] = "five" 35 | extensions[6] = "six" 36 | extensions[7] = "seven" 37 | extensions[8] = "eight" 38 | extensions[9] = "nine" 39 | extensions[10] = "ten" 40 | extensions[11] = "eleven" 41 | extensions[12] = "twelve" 42 | extensions[13] = "thirteen" 43 | extensions[14] = "fourteen" 44 | extensions[15] = "fifteen" 45 | extensions[16] = "sixteen" 46 | extensions[17] = "seventeen" 47 | extensions[18] = "eighteen" 48 | extensions[19] = "nineteen" 49 | extensions[20] = "twenty" 50 | extensions[30] = "thirty" 51 | extensions[40] = "forty" 52 | extensions[50] = "fifty" 53 | extensions[60] = "sixty" 54 | extensions[70] = "seventy" 55 | extensions[80] = "eighty" 56 | extensions[90] = "ninety" 57 | if val, ok := extensions[number]; ok { 58 | return val, true 59 | } 60 | return "", false 61 | } 62 | 63 | func decomposePowers(power int) []float64 { 64 | result := []float64{} 65 | for power >= 3 { 66 | temp := (power / 3) * 3 67 | result = append(result, float64(temp)) 68 | power -= 3 69 | } 70 | return result 71 | } 72 | 73 | 74 | func getNumberIdentity(number int) []string { 75 | // For numbers below a thousand 76 | rsvPower := len(strconv.FormatInt(int64(number), 10)) - 1 77 | 78 | result := []string{} 79 | if val, ok := getExtensions(number); ok{ 80 | result = append(result, val) 81 | rsvPower = -1 82 | } 83 | 84 | for rsvPower >= 0 { 85 | rsvPowerNum := int(math.Pow(10, float64(rsvPower))) 86 | temp, rem := number / rsvPowerNum, number % rsvPowerNum 87 | if val, ok := getExtensions(temp * rsvPowerNum); ok{ 88 | result = append(result, val) 89 | } else { 90 | if val, ok := getExtensions(temp); ok{ 91 | result = append(result, val) 92 | } 93 | } 94 | if val, ok := getPowerExtensions(rsvPower); ok{ 95 | result = append(result, val) 96 | if rem > 0{ 97 | result = append(result, "and") 98 | } 99 | } 100 | if val, ok := getExtensions(rem); ok{ 101 | result = append(result, val) 102 | rsvPower = 0 103 | } 104 | rsvPower -= 1 105 | number = rem 106 | } 107 | 108 | return result 109 | } 110 | 111 | func convertNumberToWords(number int) string{ 112 | var power float64 = float64(len(strconv.FormatInt(int64(number), 10)) - 1) 113 | result := []string{} 114 | powerArr := decomposePowers(int(power)) 115 | for _, power := range powerArr{ 116 | divisor := math.Pow(10, power) 117 | temp, rem := int(float64(number)/divisor), number % int(divisor) 118 | 119 | result = append(result, getNumberIdentity(temp)...) 120 | if powerIdentifier, ok := getPowerExtensions(int(power)); ok{ 121 | result = append(result, powerIdentifier) 122 | } 123 | number = rem 124 | } 125 | result = append(result, getNumberIdentity(number)...) 126 | return strings.Join(result, " ") 127 | } 128 | 129 | 130 | func main(){ 131 | number := flag.Int("number", 1_000, "Max number to sum to") 132 | flag.Parse() 133 | 134 | sum := 0 135 | for *number > 0{ 136 | numInWords := convertNumberToWords(*number) 137 | numInWordsStripped := strings.Replace(numInWords, " ", "", -1) 138 | sum += len(numInWordsStripped) 139 | *number -= 1 140 | } 141 | fmt.Println(sum) 142 | } 143 | 144 | 145 | -------------------------------------------------------------------------------- /Problem_18_Euler/input.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 16 | -------------------------------------------------------------------------------- /Problem_18_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | // https://projecteuler.net/problem=18 4 | 5 | import ( 6 | "bufio" 7 | "flag" 8 | "fmt" 9 | "os" 10 | "strconv" 11 | "strings" 12 | ) 13 | 14 | func DFS(arr [][]int) int { 15 | for i := len(arr[len(arr)-1]) - 2; i >= 0; i-- { 16 | for j := 0; j <= i; j++ { 17 | fmt.Println(i, j) 18 | if arr[i+1][j] > arr[i+1][j+1] { 19 | arr[i][j] += arr[i+1][j] 20 | } else { 21 | arr[i][j] += arr[i+1][j+1] 22 | } 23 | } 24 | } 25 | return arr[0][0] 26 | } 27 | 28 | func main() { 29 | 30 | fileName := flag.String("file", "input.txt", "File to read integers from") 31 | flag.Parse() 32 | 33 | input, err := os.Open(*fileName) 34 | if err != nil { 35 | panic(err) 36 | } 37 | defer input.Close() 38 | 39 | buffer := bufio.NewScanner(input) 40 | stringArr := []string{} 41 | triangleArr := [][]int{} 42 | for buffer.Scan() { 43 | numArr := []int{} 44 | stringArr = strings.Split(strings.Trim(buffer.Text(), " "), " ") 45 | for _, el := range stringArr { 46 | val, _ := strconv.Atoi(el) 47 | numArr = append(numArr, val) 48 | } 49 | triangleArr = append(triangleArr, numArr) 50 | } 51 | fmt.Println(triangleArr) 52 | result := DFS(triangleArr) 53 | fmt.Println(result) 54 | } 55 | -------------------------------------------------------------------------------- /Problem_19_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "flag" 6 | "time" 7 | ) 8 | 9 | 10 | 11 | const layoutISO = "2006-01-02" 12 | 13 | 14 | func main(){ 15 | 16 | start := flag.String("start", "1901-01-01", "Start point in format yyyy-mm-dd") 17 | end := flag.String("end", "2000-12-31", "End point in format yyyy-mm-dd") 18 | 19 | start_date, _ := time.Parse(layoutISO, *start) 20 | end_date, _ := time.Parse(layoutISO, *end) 21 | additional_date := 7 - int(start_date.Weekday()) 22 | result := 0 23 | 24 | fmt.Println(additional_date) 25 | if additional_date < 7{ 26 | start_date = start_date.Add(time.Hour * 24 * time.Duration(additional_date)) 27 | } 28 | 29 | for start_date.Unix() < end_date.Unix() { 30 | if start_date.Day() == 1 { 31 | result += 1 32 | } 33 | start_date = start_date.Add(time.Hour * 24 * 7) 34 | } 35 | fmt.Println(start_date.Day()) 36 | // result := (int(end_date.Sub(start_date).Hours() / 24) + additional_date) / 7 37 | 38 | 39 | fmt.Println(result) 40 | } 41 | -------------------------------------------------------------------------------- /Problem_1_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | 4 | // https://projecteuler.net/problem=1 5 | 6 | import "fmt" 7 | 8 | 9 | func calcArithmeticSum(a int, n int) int { 10 | if n == 0 { 11 | return 0 12 | } 13 | ans := n * (a * (n+1)) / 2 14 | fmt.Printf("Answer with a:%d and n:%d is %d\n", a, n , ans) 15 | return ans 16 | } 17 | 18 | // O(1) space and O(1) time 19 | func MultiplesOf3And5(num int) int { 20 | divBy3 := (num - 1) / 3 21 | divBy5 := (num - 1) / 5 22 | divBy15 := (num - 1) / 15 23 | return calcArithmeticSum(3, divBy3) + calcArithmeticSum(5, divBy5) - calcArithmeticSum(15, divBy15) 24 | } 25 | 26 | 27 | func main() { 28 | num := 1000 29 | ans := MultiplesOf3And5(num) 30 | fmt.Println(ans) 31 | } -------------------------------------------------------------------------------- /Problem_20_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | // https://projecteuler.net/problem=20 4 | 5 | import ( 6 | "flag" 7 | "fmt" 8 | "math/big" 9 | ) 10 | 11 | func factorial(x *big.Int) *big.Int { 12 | n := big.NewInt(1) 13 | if x.Cmp(big.NewInt(0)) == 0 { 14 | return n 15 | } 16 | return n.Mul(x, factorial(n.Sub(x, n))) 17 | } 18 | 19 | 20 | func main() { 21 | grid := flag.Int64("grid", 100, "Window of integers to return") 22 | flag.Parse() 23 | 24 | ud := factorial(big.NewInt(*grid)) 25 | result := big.NewInt(0) 26 | for ud.Cmp(big.NewInt(0)) != 0{ 27 | temp := big.NewInt(0) 28 | ud.DivMod(ud, big.NewInt(10), temp) 29 | result.Add(temp, result) 30 | } 31 | 32 | fmt.Println(result) 33 | } 34 | -------------------------------------------------------------------------------- /Problem_21_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | 4 | // https://projecteuler.net/problem=21 5 | import ( 6 | "fmt" 7 | "flag" 8 | "math" 9 | ) 10 | func getMultipleSum(num int) int{ 11 | result := []int{} 12 | sum := 0 13 | i := 2 14 | for i < int(math.Sqrt(float64(num))) { 15 | if num % i == 0 { 16 | result = append(result, num / i, i) 17 | } 18 | i++ 19 | } 20 | for _, val:= range result{ 21 | sum += val 22 | } 23 | return sum 24 | } 25 | 26 | func main(){ 27 | maxNum := flag.Int("window", 10_000, "Limit to check for amicable pairs from 0") 28 | flag.Parse() 29 | 30 | usedValues :=map[int]bool{} 31 | result := 0 32 | 33 | for *maxNum >= 2 { 34 | temp := 1 + getMultipleSum(*maxNum) 35 | if 1 + getMultipleSum(temp) == *maxNum && temp != *maxNum { 36 | if _, ok := usedValues[temp]; !ok{ 37 | if _, ok := usedValues[*maxNum]; !ok { 38 | usedValues[temp] = true 39 | usedValues[*maxNum] = true 40 | fmt.Println(temp, *maxNum) 41 | result += temp + *maxNum 42 | } 43 | } 44 | } 45 | *maxNum-- 46 | } 47 | fmt.Println(result) 48 | } 49 | -------------------------------------------------------------------------------- /Problem_22_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | 4 | // https://projecteuler.net/problem=22 5 | 6 | import ( 7 | "bufio" 8 | "fmt" 9 | "flag" 10 | "os" 11 | "sort" 12 | "strings" 13 | ) 14 | 15 | 16 | 17 | 18 | func main(){ 19 | fileName := flag.String("file", "input.txt", "File to read names from") 20 | flag.Parse() 21 | 22 | input, err := os.Open(*fileName) 23 | if err != nil { 24 | panic(err) 25 | } 26 | defer input.Close() 27 | 28 | buffer := bufio.NewScanner(input) 29 | stringArr := []string{} 30 | for buffer.Scan(){ 31 | stringArr = strings.Split(buffer.Text(), ",") 32 | sort.Strings(stringArr) 33 | } 34 | 35 | result := 0 36 | for idx, val := range stringArr{ 37 | sum := 0 38 | for _, c := range strings.ReplaceAll(val, "\"", "") { 39 | sum += int(c) - 64 40 | } 41 | result += sum * (idx + 1) 42 | } 43 | fmt.Println(result) 44 | } 45 | -------------------------------------------------------------------------------- /Problem_23_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | 4 | import ( 5 | "fmt" 6 | "flag" 7 | "math" 8 | 9 | ) 10 | 11 | 12 | func getDivisorSum(num int) int{ 13 | i := 2 14 | sum := 0 15 | for i <= int(math.Sqrt(float64(num))) { 16 | if num % i == 0 { 17 | if i != num/i { 18 | sum += i + num / i 19 | } else { 20 | sum += i 21 | } 22 | } 23 | i += 1 24 | } 25 | return sum + 1 26 | } 27 | 28 | func isUnique(number int, result map[int]bool) bool { 29 | for k, _ := range result { 30 | if _, ok := result[int(math.Abs(float64(number -k)))]; ok{ 31 | return false 32 | } 33 | 34 | } 35 | return true 36 | } 37 | 38 | func main(){ 39 | number := flag.Int("number", 28123, "Range to detect sums over") 40 | flag.Parse() 41 | 42 | /* 43 | Source: https://mathworld.wolfram.com/AbundantNumber.html 44 | Also, as opposed to the limit on the dual abundant number sum on ProjectEuler, the actual limit is 20161 45 | For abundant numbers, 46 | 1. Multiples of perfect numbers or abundant number are abundant 47 | 2. Primes are not abundant 48 | 49 | So for this solution, we can also apply an elimination method instead of a full blown search to remove numbers as such: 50 | 1. Prime numbers are deficient 51 | 2. Powers of primes are deficient 52 | 3. Perfect numbers can be excluded 53 | 4. Perfect number divisors are also deficient 54 | 5. Deficient number divisors are also deficient 55 | */ 56 | 57 | result := map[int]bool{} 58 | i := 2 59 | sum := *number * (*number + 1) / 2 60 | 61 | for i <= *number{ 62 | if i < getDivisorSum(i) { 63 | result[i] = true 64 | } 65 | if !isUnique(i, result){ 66 | sum -= i 67 | fmt.Println("Number is valid" , i) 68 | } 69 | 70 | i += 1 71 | } 72 | fmt.Println(sum) 73 | } 74 | -------------------------------------------------------------------------------- /Problem_24_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | "math" 7 | ) 8 | 9 | // https://projecteuler.net/problem=24 10 | 11 | func swap(arr []int, i int, j int) { 12 | temp := arr[i] 13 | arr[i] = arr[j] 14 | arr[j] = temp 15 | } 16 | 17 | func Reverse(s []int) []int { 18 | for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 { 19 | s[i], s[j] = s[j], s[i] 20 | } 21 | return s 22 | } 23 | 24 | 25 | func Equal(a, b []int) bool { 26 | if len(a) != len(b) { 27 | return false 28 | } 29 | for i, v := range a { 30 | if v != b[i] { 31 | return false 32 | } 33 | } 34 | return true 35 | } 36 | 37 | func factorial(x int) int { 38 | n := x 39 | if x == 0 { 40 | return 1 41 | } 42 | return n * factorial(x-1) 43 | } 44 | 45 | func main(){ 46 | window := flag.Int("window", 9, "Length of the number to generate to") 47 | index := flag.Int("index",1_000_000, "Nth lexicographic permutation to look out for") 48 | flag.Parse() 49 | 50 | arr := []int{} 51 | i := 0 52 | for i <= *window { 53 | arr = append(arr, i) 54 | i++ 55 | } 56 | 57 | fmt.Println(arr) 58 | i = 1 59 | fmt.Println(factorial(*window+1)) 60 | for i < factorial(*window + 1) { 61 | // Find the largest X 62 | largestI := -1 63 | for idx, val := range arr { 64 | if idx < len(arr) - 1 && val < arr[idx + 1] { 65 | largestI = idx 66 | } 67 | } 68 | 69 | 70 | largestJ := -1 71 | for idx, val := range arr { 72 | if arr[largestI] < val { 73 | largestJ = idx 74 | } 75 | } 76 | 77 | swap(arr, largestI, largestJ) 78 | 79 | sliceArr := Reverse(arr[largestI+1:]) 80 | 81 | arr = append(arr[:largestI+1], sliceArr...) 82 | // fmt.Println(arr) 83 | if i == *index - 1 { 84 | number := 0 85 | for idx, val := range arr { 86 | number += int(math.Pow(10, float64(len(arr) - idx - 1))) * val 87 | } 88 | fmt.Println(number) 89 | break 90 | } 91 | i += 1 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /Problem_25_Euler/.tool-versions: -------------------------------------------------------------------------------- 1 | golang 1.20.11 2 | -------------------------------------------------------------------------------- /Problem_25_Euler/differences-10.000000.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tiemma/algorithm-solutions/b259be686f62302d12f508eb798d5444bfdd3b37/Problem_25_Euler/differences-10.000000.png -------------------------------------------------------------------------------- /Problem_25_Euler/differences-100.000000.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tiemma/algorithm-solutions/b259be686f62302d12f508eb798d5444bfdd3b37/Problem_25_Euler/differences-100.000000.png -------------------------------------------------------------------------------- /Problem_25_Euler/differences-1000.000000.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tiemma/algorithm-solutions/b259be686f62302d12f508eb798d5444bfdd3b37/Problem_25_Euler/differences-1000.000000.png -------------------------------------------------------------------------------- /Problem_25_Euler/differences-10000.000000.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tiemma/algorithm-solutions/b259be686f62302d12f508eb798d5444bfdd3b37/Problem_25_Euler/differences-10000.000000.png -------------------------------------------------------------------------------- /Problem_25_Euler/differences-100000.000000.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tiemma/algorithm-solutions/b259be686f62302d12f508eb798d5444bfdd3b37/Problem_25_Euler/differences-100000.000000.png -------------------------------------------------------------------------------- /Problem_25_Euler/differences-1000000.000000.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tiemma/algorithm-solutions/b259be686f62302d12f508eb798d5444bfdd3b37/Problem_25_Euler/differences-1000000.000000.png -------------------------------------------------------------------------------- /Problem_25_Euler/differences-35.000000.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tiemma/algorithm-solutions/b259be686f62302d12f508eb798d5444bfdd3b37/Problem_25_Euler/differences-35.000000.png -------------------------------------------------------------------------------- /Problem_25_Euler/differences-40.000000.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tiemma/algorithm-solutions/b259be686f62302d12f508eb798d5444bfdd3b37/Problem_25_Euler/differences-40.000000.png -------------------------------------------------------------------------------- /Problem_25_Euler/differences-50.000000.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tiemma/algorithm-solutions/b259be686f62302d12f508eb798d5444bfdd3b37/Problem_25_Euler/differences-50.000000.png -------------------------------------------------------------------------------- /Problem_25_Euler/differences-5000.000000.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tiemma/algorithm-solutions/b259be686f62302d12f508eb798d5444bfdd3b37/Problem_25_Euler/differences-5000.000000.png -------------------------------------------------------------------------------- /Problem_25_Euler/functions-10.000000.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tiemma/algorithm-solutions/b259be686f62302d12f508eb798d5444bfdd3b37/Problem_25_Euler/functions-10.000000.png -------------------------------------------------------------------------------- /Problem_25_Euler/functions-100.000000.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tiemma/algorithm-solutions/b259be686f62302d12f508eb798d5444bfdd3b37/Problem_25_Euler/functions-100.000000.png -------------------------------------------------------------------------------- /Problem_25_Euler/functions-1000.000000.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tiemma/algorithm-solutions/b259be686f62302d12f508eb798d5444bfdd3b37/Problem_25_Euler/functions-1000.000000.png -------------------------------------------------------------------------------- /Problem_25_Euler/functions-10000.000000.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tiemma/algorithm-solutions/b259be686f62302d12f508eb798d5444bfdd3b37/Problem_25_Euler/functions-10000.000000.png -------------------------------------------------------------------------------- /Problem_25_Euler/functions-100000.000000.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tiemma/algorithm-solutions/b259be686f62302d12f508eb798d5444bfdd3b37/Problem_25_Euler/functions-100000.000000.png -------------------------------------------------------------------------------- /Problem_25_Euler/functions-1000000.000000.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tiemma/algorithm-solutions/b259be686f62302d12f508eb798d5444bfdd3b37/Problem_25_Euler/functions-1000000.000000.png -------------------------------------------------------------------------------- /Problem_25_Euler/functions-1500.000000.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tiemma/algorithm-solutions/b259be686f62302d12f508eb798d5444bfdd3b37/Problem_25_Euler/functions-1500.000000.png -------------------------------------------------------------------------------- /Problem_25_Euler/functions-35.000000.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tiemma/algorithm-solutions/b259be686f62302d12f508eb798d5444bfdd3b37/Problem_25_Euler/functions-35.000000.png -------------------------------------------------------------------------------- /Problem_25_Euler/functions-40.000000.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tiemma/algorithm-solutions/b259be686f62302d12f508eb798d5444bfdd3b37/Problem_25_Euler/functions-40.000000.png -------------------------------------------------------------------------------- /Problem_25_Euler/functions-45.000000.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tiemma/algorithm-solutions/b259be686f62302d12f508eb798d5444bfdd3b37/Problem_25_Euler/functions-45.000000.png -------------------------------------------------------------------------------- /Problem_25_Euler/functions-50.000000.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tiemma/algorithm-solutions/b259be686f62302d12f508eb798d5444bfdd3b37/Problem_25_Euler/functions-50.000000.png -------------------------------------------------------------------------------- /Problem_25_Euler/functions-500.000000.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tiemma/algorithm-solutions/b259be686f62302d12f508eb798d5444bfdd3b37/Problem_25_Euler/functions-500.000000.png -------------------------------------------------------------------------------- /Problem_25_Euler/functions-5000.000000.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tiemma/algorithm-solutions/b259be686f62302d12f508eb798d5444bfdd3b37/Problem_25_Euler/functions-5000.000000.png -------------------------------------------------------------------------------- /Problem_25_Euler/functions-5000000000.000000.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tiemma/algorithm-solutions/b259be686f62302d12f508eb798d5444bfdd3b37/Problem_25_Euler/functions-5000000000.000000.png -------------------------------------------------------------------------------- /Problem_25_Euler/functions-60.000000.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tiemma/algorithm-solutions/b259be686f62302d12f508eb798d5444bfdd3b37/Problem_25_Euler/functions-60.000000.png -------------------------------------------------------------------------------- /Problem_25_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "flag" 6 | //"image/color" 7 | "math" 8 | "math/big" 9 | 10 | //"gonum.org/v1/plot" 11 | //"gonum.org/v1/plot/plotter" 12 | //"gonum.org/v1/plot/vg" 13 | ) 14 | 15 | // // https://projecteuler.net/problem=25 16 | 17 | func getDigitLengthBinet(n int) int { 18 | // We use a reverse implementation of the Binet formula 19 | // Binet Formula gives the fibonacci digit but we can apply 20 | // A log to that to that formula to obtain the digit count 21 | if n < 2 { 22 | return 1 23 | } 24 | 25 | var phi float64= (1 + math.Sqrt(5)) / 2 26 | 27 | nDigits := float64(n) * math.Log10(phi) - (math.Log10(5) / 2) 28 | 29 | return int(math.Ceil(nDigits)) 30 | } 31 | 32 | // 33 | //func plotDifference(num float64){ 34 | // p, err := plot.New() 35 | // if err != nil { 36 | // panic(err) 37 | // } 38 | // p.Title.Text = "Differences" 39 | // p.X.Label.Text = "X" 40 | // p.Y.Label.Text = "Y" 41 | // 42 | // exp := plotter.NewFunction(func(x float64) float64 { 43 | // diff := float64(getFnIndex(int(x)) - getFnIndex(int(x - 1))) 44 | // return diff 45 | // }) 46 | // exp.Dashes = []vg.Length{vg.Points(4), vg.Points(4)} 47 | // exp.Width = vg.Points(2) 48 | // exp.Color = color.RGBA{G: 255, A: 255} 49 | // 50 | // // Add the functions and their legend entries. 51 | // p.Add(exp) 52 | // p.Legend.Add("len(F(n)) - len(F(n-1))", exp) 53 | // p.Legend.ThumbnailWidth = 2 * vg.Inch 54 | // 55 | // // Set the axis ranges. Unlike other data sets, 56 | // // functions don't set the axis ranges automatically 57 | // // since functions don't necessarily have a 58 | // // finite range of x and y values. 59 | // p.X.Min = 0 60 | // p.X.Max = num 61 | // p.Y.Min = 0 62 | // p.Y.Max = 10 63 | // 64 | // // Save the plot to a PNG file. 65 | // if err := p.Save(16*vg.Inch, 16*vg.Inch, fmt.Sprintf("differences-%1f.png", num)); err != nil { 66 | // panic(err) 67 | // } 68 | //} 69 | // 70 | // 71 | // 72 | //func plotFunc(num float64){ 73 | // p, err := plot.New() 74 | // if err != nil { 75 | // panic(err) 76 | // } 77 | // p.Title.Text = "Functions" 78 | // p.X.Label.Text = "X(5*k)" 79 | // p.Y.Label.Text = "Y(k)" 80 | // 81 | // quad := plotter.NewFunction(func(x float64) float64 { return x / 5 }) 82 | // quad.Color = color.RGBA{B: 255, A: 255} 83 | // 84 | // 85 | // exp := plotter.NewFunction(func(x float64) float64 { return float64(getDigitLengthBinet(int(x))) }) 86 | // exp.Dashes = []vg.Length{vg.Points(1), vg.Points(1)} 87 | // exp.Width = vg.Points(2) 88 | // exp.Color = color.RGBA{G: 255, A: 255} 89 | // 90 | // 91 | // sin := plotter.NewFunction(func(x float64) float64 { return - (x/5) + float64(getDigitLengthBinet(int(x))) }) 92 | // sin.Dashes = []vg.Length{vg.Points(4), vg.Points(5)} 93 | // sin.Width = vg.Points(4) 94 | // sin.Color = color.RGBA{R: 255, A: 255} 95 | // 96 | // // Add the functions and their legend entries. 97 | // p.Add(quad, exp, sin) 98 | // p.Legend.Add("5 * k", quad) 99 | // p.Legend.Add("getDigitLengthBinet", exp) 100 | // p.Legend.Add("getDigitLengthBinet - 5 * k", sin) 101 | // p.Legend.ThumbnailWidth = 2 * vg.Inch 102 | // p.Legend.Top = true 103 | // 104 | // // Set the axis ranges. Unlike other data sets, 105 | // // functions don't set the axis ranges automatically 106 | // // since functions don't necessarily have a 107 | // // finite range of x and y values. 108 | // p.X.Min = 0 109 | // p.X.Max = num 110 | // p.Y.Min = 0 111 | // p.Y.Max = num * 1 / 4 112 | // 113 | // // Save the plot to a PNG file. 114 | // if err := p.Save(16*vg.Inch, 16*vg.Inch, fmt.Sprintf("functions-%1f.png", num)); err != nil { 115 | // panic(err) 116 | // } 117 | //} 118 | 119 | 120 | func getDigitLength(n int) int{ 121 | 122 | 123 | bigFive := big.NewFloat(5) 124 | sqrt5 := big.NewFloat(1).Sqrt(bigFive) 125 | phi := big.NewFloat(1) 126 | 127 | phi.Quo(phi.Add(big.NewFloat(1), sqrt5), big.NewFloat(2)) 128 | 129 | temp := n 130 | val := big.NewFloat(1) 131 | // Raise val to the power of n 132 | // math/big doesn't have Exp on Float 133 | // So I just use a simple loop to multiply itself 134 | for temp > 0{ 135 | val = val.Mul(val, phi) 136 | temp -= 1 137 | } 138 | 139 | ans := val.Quo(val, sqrt5) 140 | 141 | 142 | fmt.Printf("Value at n: %f in fibonnaci sequence is: %f\n", n, ans) 143 | // Go returns the exp in powers of 2 144 | // 2 ^^ y == 10 ^^ x 145 | // Taking log 146 | // y log 2 = x log 10 = x 147 | // x in base10 = y log 2 hence the addition of that factor 148 | return int(float64(ans.MantExp(ans)) * math.Log10(2)) + 1 149 | } 150 | 151 | func getFnIndex(numberOfDigits int) int{ 152 | // From my analysis, the fibonacci number index follows a plot along 5x of the number 153 | // approximately in relation to its number of digits 154 | maxDelta := 5 * (numberOfDigits) 155 | 156 | for maxDelta > 0 { 157 | if numberOfDigits > getDigitLengthBinet(maxDelta) { 158 | fmt.Println("Approximate value", 5 * numberOfDigits) 159 | fmt.Println("Actual value", maxDelta + 1) 160 | fmt.Println("Offset iterations", 5 * numberOfDigits - (maxDelta + 1)) 161 | fmt.Println("Iteration Percentage", float64((5 * numberOfDigits) - (maxDelta + 1)) * 100 / float64(maxDelta + 1)) 162 | break 163 | } 164 | maxDelta -- 165 | } 166 | return maxDelta + 1 167 | } 168 | 169 | func main(){ 170 | numberOfDigits := flag.Int("number", 1_000, "Number of digits to look out for") 171 | plotGraphs := flag.Bool("plot", false, "Boolean to plot graph of deviations") 172 | flag.Parse() 173 | 174 | 175 | //maxDelta := 5 * *numberOfDigits 176 | if *plotGraphs { 177 | //pass 178 | //plotFunc(float64(maxDelta)) 179 | //plotDifference(float64(maxDelta)) 180 | } 181 | 182 | 183 | i := 2 184 | result := []int{} 185 | prevDigitCount := 1 186 | prevIndex := 0 187 | for i < *numberOfDigits{ 188 | if prevDigitCount < getDigitLengthBinet(i) { 189 | result = append(result, i - prevIndex) 190 | prevIndex = i 191 | prevDigitCount = getDigitLengthBinet(i) 192 | } 193 | i += 1 194 | } 195 | fmt.Println(result) 196 | // getDigitLength(*numberOfDigits) 197 | 198 | getFnIndex(*numberOfDigits) 199 | } 200 | -------------------------------------------------------------------------------- /Problem_26_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | 4 | import ( 5 | "flag" 6 | "fmt" 7 | ) 8 | 9 | 10 | // https://projecteuler.net/problem=26 11 | 12 | func getRepetend(numer int, denom int) int { 13 | pos := -1 14 | base := 10 15 | digitMap := map[int]int{} 16 | for { 17 | 18 | if _, ok := digitMap[numer]; ok || numer == 0 { 19 | break 20 | } 21 | digitMap[numer] = pos 22 | z := base * numer / denom 23 | numer = (numer * base) - (z * denom) 24 | fmt.Println(numer, pos) 25 | pos -= 1 26 | } 27 | 28 | return digitMap[numer] - pos 29 | } 30 | 31 | 32 | func main(){ 33 | window := flag.Int("window", 1_000, "Range to find the longest repetend in") 34 | flag.Parse() 35 | 36 | result, max := 0, 0 37 | for *window > 1 { 38 | *window -- 39 | temp := getRepetend(1, *window) 40 | if temp > max { 41 | result = * window 42 | max = temp 43 | } 44 | *window -- 45 | } 46 | fmt.Println("Digit, Length: ",result, max) 47 | } 48 | 49 | -------------------------------------------------------------------------------- /Problem_27_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "flag" 6 | "math" 7 | ) 8 | 9 | // https://projecteuler.net/problem=27 10 | 11 | func isPrime(n float64, a float64, b float64) bool{ 12 | val := math.Pow(n, 2) + (a * n) + b 13 | var i float64 = 2 14 | if val <= 1 { 15 | return false 16 | } 17 | for i <= math.Sqrt(val) { 18 | if int(val) % int(i) == 0 { 19 | return false 20 | } 21 | i += 1 22 | } 23 | return true 24 | } 25 | 26 | 27 | func main() { 28 | vala := flag.Int("a", 1_000, "Range of values for a") 29 | valb := flag.Int("b", 1_000, "Range of values for b") 30 | flag.Parse() 31 | 32 | a := - float64(*vala) 33 | var max float64 = 1 34 | var result float64 = 1 35 | fmt.Println(result) 36 | for a <= float64(*vala) { 37 | b := - float64(*valb) 38 | for b <= float64(*valb) { 39 | var n float64 = 0 40 | for isPrime(n, a, b) { 41 | n += 1 42 | } 43 | /* 44 | if n > 1 { 45 | fmt.Println(n - 2, a, b) 46 | }*/ 47 | if n - 2 > max { 48 | max = n - 2 49 | result = a * b 50 | } 51 | b += 1 52 | } 53 | a += 1 54 | } 55 | fmt.Println(result) 56 | } 57 | -------------------------------------------------------------------------------- /Problem_27_Euler/result.txt: -------------------------------------------------------------------------------- 1 | 1 2 | 0 -46 47 3 | 0 -45 47 4 | 0 -43 47 5 | 0 -42 43 6 | 0 -41 43 7 | 0 -41 47 8 | 0 -40 41 9 | 0 -39 41 10 | 0 -39 43 11 | 0 -37 41 12 | 0 -37 43 13 | 0 -37 47 14 | 0 -36 37 15 | 0 -35 37 16 | 0 -35 41 17 | 0 -35 47 18 | 0 -33 37 19 | 0 -33 43 20 | 0 -31 37 21 | 0 -31 41 22 | 0 -31 43 23 | 0 -31 47 24 | 0 -30 31 25 | 0 -29 31 26 | 0 -29 41 27 | 0 -29 47 28 | 0 -28 29 29 | 0 -27 29 30 | 0 -27 31 31 | 0 -27 37 32 | 0 -27 43 33 | 0 -25 29 34 | 0 -25 31 35 | 0 -25 37 36 | 0 -25 41 37 | 0 -25 43 38 | 0 -25 47 39 | 0 -23 29 40 | 0 -23 41 41 | 0 -22 23 42 | 0 -21 23 43 | 0 -21 31 44 | 0 -21 37 45 | 1 -21 43 46 | 0 -19 23 47 | 0 -19 29 48 | 0 -19 31 49 | 1 -19 37 50 | 1 -19 41 51 | 1 -19 47 52 | 0 -18 19 53 | 0 -17 19 54 | 0 -17 23 55 | 0 -17 29 56 | 2 -17 47 57 | 0 -16 17 58 | 0 -15 17 59 | 0 -15 19 60 | 1 -15 31 61 | 1 -15 37 62 | 2 -15 43 63 | 0 -13 17 64 | 0 -13 19 65 | 0 -13 23 66 | 1 -13 29 67 | 0 -13 31 68 | 3 -13 41 69 | 0 -13 43 70 | 0 -12 13 71 | 0 -11 13 72 | 0 -11 17 73 | 1 -11 23 74 | 2 -11 29 75 | 14 -11 41 76 | 20 -11 47 77 | 0 -10 11 78 | 0 -9 11 79 | 0 -9 13 80 | 1 -9 19 81 | 13 -9 31 82 | 19 -9 37 83 | 0 -7 11 84 | 1 -7 13 85 | 6 -7 17 86 | 0 -7 19 87 | 12 -7 23 88 | 18 -7 29 89 | 0 -7 37 90 | 0 -7 43 91 | 1 -7 47 92 | 0 -6 7 93 | 0 -5 7 94 | 5 -5 11 95 | 11 -5 17 96 | 17 -5 23 97 | 0 -5 41 98 | 41 -5 47 99 | 0 -4 5 100 | 2 -3 5 101 | 4 -3 7 102 | 10 -3 13 103 | 16 -3 19 104 | 2 -3 31 105 | 40 -3 43 106 | 1 -2 3 107 | 0 -1 2 108 | 1 -1 3 109 | 3 -1 5 110 | 0 -1 7 111 | 9 -1 11 112 | 0 -1 13 113 | 15 -1 17 114 | 0 -1 19 115 | 0 -1 23 116 | 1 -1 29 117 | 0 -1 31 118 | 0 -1 37 119 | 39 -1 41 120 | 0 -1 43 121 | 0 -1 47 122 | 0 0 2 123 | 0 1 3 124 | 2 1 5 125 | 8 1 11 126 | 14 1 17 127 | 0 1 29 128 | 38 1 41 129 | 0 2 2 130 | 1 3 3 131 | 1 3 7 132 | 7 3 13 133 | 13 3 19 134 | 1 3 37 135 | 37 3 43 136 | 0 4 2 137 | 3 5 5 138 | 0 5 7 139 | 0 5 11 140 | 0 5 13 141 | 6 5 17 142 | 12 5 23 143 | 0 5 31 144 | 0 5 37 145 | 0 5 41 146 | 36 5 47 147 | 0 7 3 148 | 1 7 5 149 | 2 7 11 150 | 5 7 23 151 | 11 7 29 152 | 0 8 2 153 | 0 9 3 154 | 3 9 7 155 | 0 9 13 156 | 1 9 19 157 | 4 9 31 158 | 10 9 37 159 | 0 9 43 160 | 0 10 2 161 | 2 11 5 162 | 0 11 7 163 | 3 11 11 164 | 2 11 17 165 | 0 11 19 166 | 0 11 29 167 | 0 11 31 168 | 3 11 41 169 | 9 11 47 170 | 0 13 3 171 | 0 13 5 172 | 1 13 17 173 | 2 13 23 174 | 1 13 29 175 | 0 13 47 176 | 0 14 2 177 | 1 15 3 178 | 4 15 7 179 | 9 15 13 180 | 0 15 31 181 | 1 15 37 182 | 0 15 43 183 | 0 16 2 184 | 1 17 5 185 | 0 17 11 186 | 0 17 13 187 | 0 17 19 188 | 3 17 23 189 | 8 17 29 190 | 2 17 41 191 | 0 17 43 192 | 0 19 3 193 | 1 19 11 194 | 13 19 17 195 | 0 19 23 196 | 2 19 41 197 | 7 19 47 198 | 0 20 2 199 | 4 21 7 200 | 0 21 19 201 | 0 21 31 202 | 12 21 37 203 | 0 23 5 204 | 0 23 7 205 | 0 23 13 206 | 1 23 17 207 | 0 23 19 208 | 15 23 23 209 | 3 23 29 210 | 0 23 37 211 | 0 23 43 212 | 1 23 47 213 | 0 25 3 214 | 2 25 5 215 | 0 25 11 216 | 2 25 17 217 | 0 25 41 218 | 14 25 47 219 | 0 26 2 220 | 1 27 3 221 | 10 27 13 222 | 0 27 19 223 | 1 27 31 224 | 1 27 43 225 | 0 28 2 226 | 0 29 7 227 | 2 29 11 228 | 0 29 13 229 | 3 29 17 230 | 0 29 23 231 | 0 29 29 232 | 0 29 31 233 | 0 29 37 234 | 9 29 41 235 | 0 29 43 236 | 2 31 5 237 | 0 31 11 238 | 0 31 29 239 | 1 31 41 240 | 2 31 47 241 | 1 33 3 242 | 0 33 7 243 | 1 33 13 244 | 3 33 19 245 | 1 33 37 246 | 0 34 2 247 | 1 35 5 248 | 0 35 7 249 | 0 35 11 250 | 0 35 17 251 | 8 35 23 252 | 0 35 31 253 | 0 35 37 254 | 0 35 43 255 | 0 35 47 256 | 0 37 3 257 | 1 37 5 258 | 1 37 23 259 | 4 37 29 260 | 0 37 41 261 | 0 38 2 262 | 0 39 3 263 | 1 39 7 264 | 0 39 13 265 | 1 39 19 266 | 2 39 31 267 | 0 39 43 268 | 0 40 2 269 | 0 41 5 270 | 1 41 11 271 | 3 41 17 272 | 0 41 19 273 | 0 41 29 274 | 0 41 31 275 | 0 41 37 276 | 2 41 41 277 | 0 41 47 278 | 0 43 3 279 | 1 43 17 280 | 1 43 23 281 | 0 43 29 282 | 0 44 2 283 | 2 45 7 284 | 2 45 13 285 | 3 45 37 286 | 1 45 43 287 | 1 47 5 288 | 1 47 11 289 | 0 47 13 290 | 0 47 19 291 | 0 47 23 292 | 0 47 31 293 | 2 47 41 294 | 0 49 3 295 | 4 49 11 296 | 0 49 17 297 | 0 49 23 298 | 1 49 29 299 | 1 49 47 300 | 0 50 2 301 | -------------------------------------------------------------------------------- /Problem_28_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | ) 7 | 8 | // https://projecteuler.net/problem=28 9 | 10 | 11 | func diagonalDifferenceFactor(num int) int { 12 | return num - 1 13 | } 14 | 15 | func topRight(num int) int { 16 | return num * num 17 | } 18 | 19 | func topLeft(num int) int { 20 | return topRight(num) - diagonalDifferenceFactor(num) 21 | } 22 | 23 | func bottomLeft(num int) int { 24 | return topRight(num) - (4 * (diagonalDifferenceFactor(num) / 2)) 25 | } 26 | 27 | func bottomRight(num int) int { 28 | return topRight(num) - (3 * diagonalDifferenceFactor(num)) 29 | } 30 | 31 | func main() { 32 | grid := flag.Int("grid", 1_001, "Spiral width along the diagonal") 33 | flag.Parse() 34 | 35 | sum := 1 36 | i := 3 37 | for i <= *grid{ 38 | sum += topRight(i) + topLeft(i) + bottomLeft(i) + bottomRight(i) 39 | i += 2 40 | } 41 | fmt.Println(sum) 42 | } 43 | -------------------------------------------------------------------------------- /Problem_29_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | // https://projecteuler.net/problem=29 4 | 5 | import ( 6 | "flag" 7 | "fmt" 8 | "math/big" 9 | ) 10 | 11 | func main() { 12 | a := flag.Int("a", 100, "Window for power combination as value") 13 | b := flag.Int("b", 100, "Window for power combination as power") 14 | 15 | flag.Parse() 16 | mem := map[string]bool{} 17 | count := 2 18 | for *a >= count { 19 | temp := 2 20 | for *b >= temp { 21 | val := big.NewInt(1) 22 | val.Exp(big.NewInt(int64(count)), big.NewInt(int64(temp)), nil) 23 | mem[val.String()] = true 24 | temp ++ 25 | } 26 | count ++ 27 | } 28 | fmt.Println(len(mem)) 29 | } 30 | -------------------------------------------------------------------------------- /Problem_29_Euler/main.py: -------------------------------------------------------------------------------- 1 | 2 | def get_distinct_count(a = 100, b = 100): 3 | mem = set() 4 | count = 2 5 | while a >= count: 6 | temp = 2 7 | while b >= temp: 8 | mem.add(count**temp) 9 | temp += 1 10 | count+=1 11 | print(mem) 12 | return len(set(mem)) 13 | 14 | 15 | if __name__ == "__main__": 16 | print(get_distinct_count(100, 100)) 17 | 18 | -------------------------------------------------------------------------------- /Problem_2_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | // https://projecteuler.net/problem=2 4 | 5 | 6 | import ( 7 | "fmt" 8 | "math" 9 | ) 10 | 11 | func BinetFormula(n float64) float64 { 12 | sqrt5 := math.Sqrt(5) 13 | phi := (1 + sqrt5) / 2 14 | ans := math.Round(math.Pow(phi, n) / sqrt5) 15 | fmt.Printf("Value at n: %f in fibonnaci sequence is: %f\n", n, ans) 16 | return ans 17 | } 18 | 19 | // O(n) time and space 20 | // n - Number of even fibonacci occurrences 21 | func FibonnaciSum() int { 22 | currValue := 0.0 23 | n := 3.0 24 | maxValue := 4* math.Pow(10, 6) 25 | for BinetFormula(n) < maxValue { 26 | currValue += BinetFormula(n) 27 | fmt.Println(currValue) 28 | // 1 2 3 5 8 13 21 34.... 29 | // Following the sequence, we see that the index for even numbers occurs at steps of 3 30 | // 1 4 7 .... 31 | // So no need to bother with the other sequences, just increment the index by 3 and move to the next even one 32 | n += 3 33 | } 34 | return int(currValue) 35 | } 36 | 37 | func main(){ 38 | fmt.Println(FibonnaciSum()) 39 | } 40 | -------------------------------------------------------------------------------- /Problem_30_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | "math" 7 | ) 8 | 9 | 10 | func getDigitPowerSum(num float64, power float64) float64{ 11 | sum := *new(float64) 12 | for num > 0{ 13 | sum += math.Pow(math.Mod(num, 10), power) 14 | num = math.Floor(num / 10) 15 | } 16 | return sum 17 | } 18 | 19 | func main(){ 20 | power := flag.Float64("power", 5, "Power to raise individual digits to") 21 | flag.Parse() 22 | 23 | 24 | limit := math.Pow(9, *power) * *power 25 | sum := *new(float64) 26 | for limit > 9 { 27 | if limit == getDigitPowerSum(limit, *power) { 28 | sum += limit 29 | } 30 | limit -- 31 | } 32 | fmt.Println(sum) 33 | } 34 | 35 | -------------------------------------------------------------------------------- /Problem_31_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | 4 | import ( 5 | "flag" 6 | "fmt" 7 | ) 8 | 9 | func main(){ 10 | amount := flag.Int("amount", 200, "Amount to get from permutative sums") 11 | flag.Parse() 12 | 13 | coins := []int{1, 2, 5, 10, 20, 50, 100, 200} 14 | sum := make([]int, *amount) 15 | sum = append([]int{1}, sum...) 16 | for _, val := range coins { 17 | for j := val; j <= *amount; j++ { 18 | sum[j] += sum[j - val] 19 | } 20 | } 21 | fmt.Println(sum[*amount]) 22 | 23 | } 24 | -------------------------------------------------------------------------------- /Problem_32_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "sort" 6 | "strconv" 7 | "strings" 8 | ) 9 | 10 | // https://projecteuler.net/problem=33 11 | 12 | func splitInt(n int) []string { 13 | return strings.Split(strconv.Itoa(n), "") 14 | } 15 | 16 | func hasPanFactors(n int) bool { 17 | for i := 1; i * i <= n; i++ { 18 | s := splitInt(n) 19 | 20 | if n % i == 0 { 21 | s = append(s, splitInt(i)...) 22 | s = append(s, splitInt(n / i)...) 23 | } 24 | 25 | sort.Strings(s) 26 | 27 | if strings.Join(s, "") == "123456789" { 28 | return true 29 | } 30 | } 31 | 32 | return false 33 | } 34 | 35 | func main() { 36 | sum := 0 37 | for i := 1; i < 10000; i++ { 38 | if hasPanFactors(i) { 39 | sum += i 40 | } 41 | } 42 | 43 | fmt.Println("=====") 44 | fmt.Println(sum) 45 | } -------------------------------------------------------------------------------- /Problem_33_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func gcd(a, b int) int { 6 | if b == 0 { 7 | return a 8 | } 9 | 10 | return gcd(b, a%b) 11 | } 12 | 13 | func main() { 14 | dp, np := 1, 1 15 | for c := 1; c <= 9; c++ { 16 | for d := 1; d < c; d++ { 17 | for n := 1; n < d; n++ { 18 | if ((n * 10) + c) * d == ((c * 10) + d) * n { 19 | np *= n 20 | dp *= d 21 | fmt.Println(c, n, d) 22 | } 23 | } 24 | } 25 | } 26 | 27 | fmt.Println(dp / gcd(np, dp)) 28 | } -------------------------------------------------------------------------------- /Problem_34_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | // https://projecteuler.net/problem=34 4 | 5 | import ( 6 | "fmt" 7 | ) 8 | 9 | 10 | func FactorialSum(prev map[int]int, num int) int { 11 | result := 0 12 | for num > 0 { 13 | remainder := num - (10 * (num/10)) 14 | result += prev[remainder] 15 | num = num/10 16 | } 17 | 18 | return result 19 | } 20 | 21 | 22 | func main() { 23 | prevFactorial := map[int]int{0: 1, 1: 1} 24 | for i := 2; i < 10; i++ { 25 | prevFactorial[i] = prevFactorial[i-1] * i 26 | } 27 | fmt.Println(prevFactorial) 28 | 29 | 30 | i := 3 31 | result := 0 32 | //map[0:1 1:1 2:2 3:6 4:24 5:120 6:720 7:5040 8:40320 9:362880] 33 | // To get the largest factorial that can be a sum, it cannot be bigger than the largest factorial starting 34 | // the sum which is 9!. Anything beyond that is impossible. 35 | for i < prevFactorial[9] { 36 | factorialSum := FactorialSum(prevFactorial, i) 37 | if i == factorialSum { 38 | fmt.Println(i, factorialSum) 39 | result += i 40 | } 41 | i++ 42 | } 43 | 44 | fmt.Println(result) 45 | } 46 | 47 | -------------------------------------------------------------------------------- /Problem_35_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | // https://projecteuler.net/problem=35 4 | 5 | import ( 6 | "flag" 7 | "fmt" 8 | "math" 9 | "strconv" 10 | ) 11 | 12 | 13 | func isPrime(n int) bool { 14 | sqrt := int(math.Sqrt(float64(n))) + 1 15 | for i := 2; i < sqrt; i++ { 16 | if n%i == 0 { 17 | return false 18 | } 19 | } 20 | 21 | return true 22 | } 23 | 24 | func rotateDigit(n int) int { 25 | remainder := n - (10 * (n/10)) 26 | power := float64(len(strconv.Itoa(n))) - 1 27 | 28 | return (remainder * int(math.Pow(10, power))) + (n/10) 29 | } 30 | 31 | func isCircularPrime(n int) bool { 32 | newDigit := rotateDigit(n) 33 | 34 | for n != newDigit { 35 | if !isPrime(newDigit) { 36 | return false 37 | } 38 | newDigit = rotateDigit(newDigit) 39 | } 40 | 41 | return true 42 | } 43 | 44 | 45 | func main() { 46 | window := flag.Float64("window", 1_000_000, "Window to search for circular primes") 47 | flag.Parse() 48 | 49 | count := 0 50 | for i := 2; i < int(*window); i++ { 51 | if isPrime(i) && isCircularPrime(i) { 52 | fmt.Println(i) 53 | count += 1 54 | } 55 | } 56 | 57 | fmt.Println("-----------") 58 | fmt.Println(count) 59 | } 60 | 61 | -------------------------------------------------------------------------------- /Problem_36_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | // https://projecteuler.net/problem=36 4 | 5 | import ( 6 | "flag" 7 | "fmt" 8 | "strconv" 9 | ) 10 | 11 | func isPalindrome(numStr string) bool { 12 | return numStr == Reverse(numStr) 13 | } 14 | 15 | func Reverse(s string) string { 16 | runes := []rune(s) 17 | for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 { 18 | runes[i], runes[j] = runes[j], runes[i] 19 | } 20 | return string(runes) 21 | } 22 | 23 | func main() { 24 | window := flag.Float64("window", 1_000_000, "Window to search for circular primes") 25 | flag.Parse() 26 | 27 | result := 0 28 | for i := 1; i < int(*window); i++ { 29 | if isPalindrome(strconv.Itoa(i)) && isPalindrome(strconv.FormatInt(int64(i), 2)) { 30 | fmt.Println(i) 31 | result += i 32 | } 33 | } 34 | 35 | fmt.Println("-----------") 36 | fmt.Println(result) 37 | } 38 | 39 | -------------------------------------------------------------------------------- /Problem_37_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | // https://projecteuler.net/problem=37 4 | 5 | import ( 6 | "fmt" 7 | ) 8 | 9 | func main() { 10 | // It is redundant to find the truncatable primes using math so I just pull them online 11 | // There are 15 primes which are both left-truncatable and right-truncatable. They have been called two-sided primes. The complete list: 2, 3, 5, 7, 23, 37, 53, 73, 313, 317, 373, 797, 3137, 3797, 739397 (sequence A020994 in the OEIS) 12 | // In the problem statement, 2, 3, 5 and 7 are not allowed hence the number being 11. 13 | numbers := []int{23, 37, 53, 73, 313, 317, 373, 797, 3137, 3797, 739397} 14 | result := 0 15 | for _, i := range numbers { 16 | result += i 17 | } 18 | 19 | fmt.Println(result) 20 | } 21 | 22 | -------------------------------------------------------------------------------- /Problem_38_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | // https://projecteuler.net/problem=38 4 | 5 | import ( 6 | "fmt" 7 | "math" 8 | ) 9 | 10 | // https://en.wikipedia.org/wiki/Heap%27s_algorithm 11 | func getPermutations(arr []int)[][]int{ 12 | var helper func([]int, int) 13 | res := [][]int{} 14 | 15 | helper = func(arr []int, n int){ 16 | if n == 1{ 17 | tmp := make([]int, len(arr)) 18 | copy(tmp, arr) 19 | res = append(res, tmp) 20 | } else { 21 | for i := 0; i < n; i++{ 22 | helper(arr, n - 1) 23 | if n % 2 == 1{ 24 | tmp := arr[i] 25 | arr[i] = arr[n - 1] 26 | arr[n - 1] = tmp 27 | } else { 28 | tmp := arr[0] 29 | arr[0] = arr[n - 1] 30 | arr[n - 1] = tmp 31 | } 32 | } 33 | } 34 | } 35 | helper(arr, len(arr)) 36 | return res 37 | } 38 | 39 | func getValue(digits []int) int{ 40 | value := 0 41 | for i := 0; i < len(digits); i++ { 42 | value += int(math.Pow(10, float64(i))) * digits[len(digits)-i-1] 43 | } 44 | 45 | return value 46 | } 47 | 48 | func getValueAndRemainder(x, y int) (int, int) { 49 | return x/y, x%y 50 | } 51 | 52 | func isPandigitalMultiple(digits []int) bool{ 53 | numbers := []int{} 54 | for i := 1; i < 5; i++ { 55 | lastMultiple := 1 56 | divisor := getValue(digits[:i]) 57 | numbers = append(numbers, divisor) 58 | newDigits := digits[i:] 59 | idx := i 60 | for len(newDigits) > 0 { 61 | if idx > len(newDigits) { 62 | break 63 | } 64 | multiple := getValue(newDigits[:idx]) 65 | value, remainder := getValueAndRemainder(multiple, divisor) 66 | if value > lastMultiple + 1 { 67 | numbers = []int{} 68 | break 69 | } 70 | if !(value == lastMultiple + 1 && remainder == 0) { 71 | idx += 1 72 | continue 73 | } 74 | newDigits = newDigits[idx:] 75 | lastMultiple += 1 76 | numbers = append(numbers, multiple) 77 | 78 | if len(newDigits) == 0 { 79 | return true 80 | } 81 | } 82 | } 83 | 84 | return false 85 | } 86 | 87 | 88 | func main() { 89 | digits := []int{} 90 | for i := 1; i < 10; i++ { 91 | digits = append(digits, i) 92 | } 93 | 94 | value := math.MinInt64 95 | for _, numbers := range getPermutations(digits) { 96 | if isPandigitalMultiple(numbers) { 97 | newValue := getValue(numbers) 98 | fmt.Println(newValue) 99 | if value < newValue{ 100 | value = newValue 101 | } 102 | } 103 | } 104 | 105 | fmt.Println("--------------") 106 | fmt.Println(value) 107 | 108 | } 109 | 110 | -------------------------------------------------------------------------------- /Problem_39_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | // https://projecteuler.net/problem=39 4 | 5 | import ( 6 | "flag" 7 | "fmt" 8 | "math" 9 | ) 10 | 11 | func main() { 12 | window := flag.Float64("window", 1_000, "Window to search for the perimeter values") 13 | flag.Parse() 14 | 15 | // From my article: https://blog.bakman.build/blogs/unravelling-mathematical-threesomes.html 16 | // You can obtain a pythagorean triples using just one value "b" and some pythagorean distance "k" 17 | // So perimeter = a + b + c = (b^2 / k) + b 18 | // perimeter = (b^2 / k) + b 19 | // k = b ^ 2 / (perimeter - b) 20 | 21 | // To solve this, k must be an integer based on the equation above 22 | // In getting b, we can conclude that it is always bounded within 23 | // perimeter/2 as no pythagorean value can be greater than its perimeter halved. 24 | // If we consider that the longest side, the hypotenus "c" is less than the perimeter halved: 25 | // (a + b + c) / 2 > c 26 | // a + b + c > 2c 27 | // a + b > c 28 | // a + b > sqrt(a^2 + b^2) which will hold true as 29 | // (a + b)^ 2 > a^2 + b^2 by 2ab once you expand the factors 30 | 31 | // The solution is maximised when the greater number of whole values of k that give whole values of a, b and c are obtained 32 | // This is therefore a search for the number of values from 0 to perimeter / 2 that satisfies those constraints 33 | maxPerimeter, maxCount := math.MinInt64, 0 34 | for perimeter := 2; perimeter < int(*window); perimeter++ { 35 | count := 0 36 | for b := 2; b < perimeter/2; b++ { 37 | if int(math.Pow(float64(b), 2))%int(perimeter-b) == 0 { 38 | k := math.Pow(float64(b), 2) / float64(perimeter-b) 39 | bsquared := math.Pow(float64(b), 2) 40 | c := 0.5 * (bsquared/k + k) 41 | a := 0.5 * (bsquared/k - k) 42 | // Fractional results are not needed here 43 | if c > math.Floor(c) || a > math.Floor(a) { 44 | continue 45 | } 46 | count += 1 47 | } 48 | } 49 | 50 | if count > maxCount { 51 | maxPerimeter = perimeter 52 | maxCount = count 53 | fmt.Println(maxPerimeter, maxCount) 54 | } 55 | } 56 | 57 | fmt.Println("----------------") 58 | // We will have a and b as individual values for the result hence we get double the actual number of values 59 | // It doesn't matter anyways as the answer does not require unique entries for the pythagorean triples 60 | fmt.Println(maxPerimeter, maxCount) 61 | } 62 | -------------------------------------------------------------------------------- /Problem_3_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | 4 | // https://projecteuler.net/problem=3 5 | 6 | import ( 7 | "fmt" 8 | "math" 9 | ) 10 | 11 | func DivMod(n float64, d float64) (float64, int) { 12 | return n / d, int(n) % int(d) 13 | } 14 | 15 | // O(n) time and O(1) space 16 | func PrimeCheck(n float64) float64 { 17 | largestSqrt := math.Round(math.Sqrt(n)) 18 | ans := 0.0 19 | for i := 2.0; i < largestSqrt; i++ { 20 | temp, rem := DivMod(n, i) 21 | if rem == 0 { 22 | n = temp 23 | ans = math.Max(ans, i) 24 | } 25 | } 26 | ans = math.Max(ans, n) 27 | 28 | return ans 29 | } 30 | 31 | 32 | func main(){ 33 | fmt.Println(PrimeCheck(600851475143)) 34 | } -------------------------------------------------------------------------------- /Problem_40_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | "math" 7 | ) 8 | 9 | // https://projecteuler.net/problem=40 10 | 11 | func getValueAndRemainder(x int, y int) (int, int) { 12 | return x / y, x % y 13 | } 14 | 15 | func digit(num, place int) int { 16 | fmt.Println(num, place) 17 | r := num % int(math.Pow(10, float64(place))) 18 | return r / int(math.Pow(10, float64(place-1))) 19 | } 20 | 21 | func getDigitLengthAtIndex(idx int, numLength map[int]int) int { 22 | for i := 0; i < math.MaxInt64; i++ { 23 | if numLength[i] > idx { 24 | return i 25 | } 26 | } 27 | 28 | return -1 29 | } 30 | 31 | func getDigitAtIndex(idx int, numLength map[int]int) int { 32 | k := getDigitLengthAtIndex(idx, numLength) 33 | adjustedStart := numLength[k-1] + 1 34 | value, remainder := getValueAndRemainder(idx-adjustedStart, k) 35 | fmt.Println(value, remainder) 36 | 37 | return digit(int(math.Pow(10, float64(k-1)))+value, k-remainder) 38 | } 39 | 40 | func main() { 41 | maxPower := flag.Float64("window", 1_000_000, "Window to generate powers of 10 for digits") 42 | flag.Parse() 43 | 44 | numLength := map[int]int{} 45 | numLength[0] = 0 46 | for i := 1; i <= int(math.Log10(*maxPower)); i++ { 47 | numLength[i] = numLength[i-1] + int(math.Pow(10, float64(i))-math.Pow(10, float64(i-1)))*i 48 | } 49 | fmt.Println(numLength) 50 | 51 | result := 1 52 | for i := 0; i <= int(math.Log10(*maxPower)); i++ { 53 | idx := int(math.Pow(10, float64(i))) 54 | number := getDigitAtIndex(idx, numLength) 55 | result = result * number 56 | fmt.Println(idx, number, result) 57 | fmt.Println("------------------") 58 | } 59 | 60 | fmt.Println("------------------") 61 | fmt.Println(result) 62 | 63 | } 64 | -------------------------------------------------------------------------------- /Problem_41_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "math" 6 | ) 7 | 8 | // https://projecteuler.net/problem=41 9 | 10 | // https://en.wikipedia.org/wiki/Heap%27s_algorithm 11 | func getPermutations(arr []int) [][]int { 12 | var helper func([]int, int) 13 | res := [][]int{} 14 | 15 | helper = func(arr []int, n int) { 16 | if n == 1 { 17 | tmp := make([]int, len(arr)) 18 | copy(tmp, arr) 19 | res = append(res, tmp) 20 | } else { 21 | for i := 0; i < n; i++ { 22 | helper(arr, n-1) 23 | if n%2 == 1 { 24 | tmp := arr[i] 25 | arr[i] = arr[n-1] 26 | arr[n-1] = tmp 27 | } else { 28 | tmp := arr[0] 29 | arr[0] = arr[n-1] 30 | arr[n-1] = tmp 31 | } 32 | } 33 | } 34 | } 35 | helper(arr, len(arr)) 36 | return res 37 | } 38 | 39 | func getValue(digits []int) int { 40 | value := 0 41 | for i := 0; i < len(digits); i++ { 42 | value += int(math.Pow(10, float64(i))) * digits[len(digits)-i-1] 43 | } 44 | 45 | return value 46 | } 47 | 48 | func isPrime(n int) bool { 49 | sqrt := int(math.Sqrt(float64(n))) + 1 50 | for i := 2; i < sqrt; i++ { 51 | if n%i == 0 { 52 | return false 53 | } 54 | } 55 | 56 | return true 57 | } 58 | 59 | func main() { 60 | digits := []int{} 61 | for i := 1; i < 10; i++ { 62 | digits = append(digits, i) 63 | } 64 | 65 | maxPandigitalPrime := math.MinInt64 66 | 67 | for len(digits) > 0 { 68 | newDigits := make([]int, len(digits)) 69 | copy(newDigits, digits) 70 | for _, perm := range getPermutations(newDigits) { 71 | number := getValue(perm) 72 | if isPrime(number) && number > maxPandigitalPrime { 73 | fmt.Println(number) 74 | maxPandigitalPrime = number 75 | } 76 | } 77 | 78 | digits = digits[:len(digits)-1] 79 | } 80 | 81 | fmt.Println("---------------") 82 | fmt.Println(maxPandigitalPrime) 83 | } 84 | -------------------------------------------------------------------------------- /Problem_42_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "math" 6 | "os" 7 | "strings" 8 | ) 9 | 10 | // https://projecteuler.net/problem=42 11 | 12 | func isTriangleWord(c int) bool { 13 | a := 1.0 14 | b := 1.0 15 | firstRoot := (-b + math.Sqrt(math.Pow(b, 2)-(4*a*float64(c)))) / (2 * a) 16 | secondRoot := (-b - math.Sqrt(math.Pow(b, 2)-(4*a*float64(c)))) / (2 * a) 17 | 18 | return math.Floor(firstRoot) == firstRoot && math.Floor(secondRoot) == secondRoot 19 | } 20 | 21 | func convertWordToNumber(word string) int { 22 | result := 0 23 | 24 | for i := 1; i < len(word)-1; i++ { 25 | result += int(word[i]-'A') + 1 26 | } 27 | 28 | return result 29 | } 30 | 31 | func main() { 32 | content, err := os.ReadFile("words.txt") 33 | if err != nil { 34 | panic(err) 35 | } 36 | 37 | // In this case, we use prime factorization via the quadratic formula 38 | // ax^2 + bx + c = 0 39 | // n/2(n+1) = c 40 | // n^2 + n = 2c 41 | // n^2 + n - 2c = 0 42 | // All that's done here is converting the number to an int and multiplying the value by -2 43 | // To check if it's a triangle word is just simple arithmetic to verify the roots are whole numbers 44 | lines := strings.Split(string(content), ",") 45 | count := 0 46 | for _, line := range lines { 47 | if isTriangleWord(-2 * convertWordToNumber(line)) { 48 | count += 1 49 | } 50 | } 51 | 52 | fmt.Println(count) 53 | } 54 | -------------------------------------------------------------------------------- /Problem_43_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "math" 6 | ) 7 | 8 | // https://projecteuler.net/problem=43 9 | 10 | // https://en.wikipedia.org/wiki/Heap%27s_algorithm 11 | func getPermutations(arr []int) [][]int { 12 | var helper func([]int, int) 13 | res := [][]int{} 14 | 15 | helper = func(arr []int, n int) { 16 | if n == 1 { 17 | tmp := make([]int, len(arr)) 18 | copy(tmp, arr) 19 | res = append(res, tmp) 20 | } else { 21 | for i := 0; i < n; i++ { 22 | helper(arr, n-1) 23 | if n%2 == 1 { 24 | tmp := arr[i] 25 | arr[i] = arr[n-1] 26 | arr[n-1] = tmp 27 | } else { 28 | tmp := arr[0] 29 | arr[0] = arr[n-1] 30 | arr[n-1] = tmp 31 | } 32 | } 33 | } 34 | } 35 | helper(arr, len(arr)) 36 | return res 37 | } 38 | 39 | func getValue(digits []int) int { 40 | value := 0 41 | for i := 0; i < len(digits); i++ { 42 | value += int(math.Pow(10, float64(i))) * digits[len(digits)-i-1] 43 | } 44 | 45 | return value 46 | } 47 | 48 | func isPrime(n int) bool { 49 | sqrt := int(math.Sqrt(float64(n))) + 1 50 | for i := 2; i < sqrt; i++ { 51 | if n%i == 0 { 52 | return false 53 | } 54 | } 55 | 56 | return true 57 | } 58 | 59 | func main() { 60 | digits := []int{} 61 | for i := 0; i < 10; i++ { 62 | digits = append(digits, i) 63 | } 64 | 65 | maxPandigitalPrime := 0 66 | 67 | primes := map[int]int{} 68 | for i := 2; i < math.MaxInt64; i++ { 69 | if len(primes) > 6 { 70 | break 71 | } 72 | 73 | if isPrime(i) { 74 | primes[len(primes)+1] = i 75 | } 76 | } 77 | 78 | for _, perm := range getPermutations(digits) { 79 | number := getValue(perm) 80 | isDivisible := true 81 | 82 | for i := 1; i < len(digits)-2; i++ { 83 | newDigits := perm[i : i+3] 84 | if getValue(newDigits)%primes[i] != 0 { 85 | isDivisible = false 86 | break 87 | } 88 | } 89 | 90 | if isDivisible { 91 | fmt.Println(number) 92 | maxPandigitalPrime += number 93 | } 94 | 95 | } 96 | 97 | fmt.Println("---------------") 98 | fmt.Println(maxPandigitalPrime) 99 | } 100 | -------------------------------------------------------------------------------- /Problem_44_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "math" 6 | ) 7 | 8 | // https://projecteuler.net/problem=44 9 | 10 | func getPentagonalNumber(n int) int { 11 | return n * (3*n - 1) / 2 12 | } 13 | 14 | func main() { 15 | // In the series, it is quadratic and monotonically increasing 16 | // I assume a max range to search for the minimum distance between two pentagon numbers 17 | // After finding the first distance, any other distance greater than it confirms our proof of divergence and we can stop there 18 | values := map[int]struct{}{} 19 | minDistance := math.MaxInt 20 | for i := 1; i < math.MaxInt; i++ { 21 | number := getPentagonalNumber(i) 22 | values[number] = struct{}{} 23 | for j, _ := range values { 24 | if j > number/2 { 25 | continue 26 | } 27 | if _, ok := values[number-j]; ok { 28 | D := number - 2*j 29 | if _, ok := values[D]; ok { 30 | fmt.Println(i, number, j, number-j, D) 31 | if D < minDistance { 32 | minDistance = D 33 | } else { 34 | break 35 | } 36 | } 37 | } 38 | } 39 | 40 | if minDistance != math.MaxInt { 41 | break 42 | } 43 | } 44 | 45 | fmt.Println(minDistance) 46 | } 47 | -------------------------------------------------------------------------------- /Problem_45_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "math" 6 | ) 7 | 8 | // https://projecteuler.net/problem=45 9 | 10 | func getQuadraticRoots(a, b, c float64) (float64, float64) { 11 | firstRoot := (-b + math.Sqrt(math.Pow(b, 2)-(4*a*float64(c)))) / (2 * a) 12 | secondRoot := (-b - math.Sqrt(math.Pow(b, 2)-(4*a*float64(c)))) / (2 * a) 13 | 14 | return firstRoot, secondRoot 15 | } 16 | 17 | func isValidRoot(ft, st, fp, sp, fh, sh float64) bool { 18 | for _, roots := range [][]float64{{ft, st}, {fp, sp}, {fh, sh}} { 19 | isValid := 0 20 | for _, root := range roots { 21 | if root > 0 && math.Floor(root) == root { 22 | isValid += 1 23 | } 24 | } 25 | 26 | if isValid == 0 { 27 | return false 28 | } 29 | } 30 | 31 | return true 32 | } 33 | 34 | func hexagonalNumber(c int) int { 35 | return c * (2*c - 1) 36 | } 37 | 38 | func main() { 39 | for k := 144; k < math.MaxInt; k++ { 40 | i := float64(hexagonalNumber(k)) 41 | ft, st := getQuadraticRoots(0.5, 0.5, -i) 42 | fp, sp := getQuadraticRoots(1.5, -0.5, -i) 43 | fh, sh := getQuadraticRoots(2, -1, -i) 44 | 45 | if isValidRoot(ft, st, fp, sp, fh, sh) { 46 | fmt.Println(ft, st, fp, sp, fh, sh) 47 | fmt.Println(k, int64(i)) 48 | 49 | return 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /Problem_46_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "math" 6 | ) 7 | 8 | // https://projecteuler.net/problem=46 9 | 10 | func isPrime(n int) bool { 11 | sqrt := int(math.Sqrt(float64(n))) + 1 12 | for i := 2; i < sqrt; i++ { 13 | if n%i == 0 { 14 | return false 15 | } 16 | } 17 | 18 | return true 19 | } 20 | 21 | func isValidGoldbachConjecture(n int, primes []int) bool { 22 | for _, prime := range primes { 23 | if n < prime { 24 | break 25 | } 26 | 27 | number := math.Sqrt(0.5 * float64(n-prime)) 28 | 29 | if math.Floor(number) == number { 30 | return true 31 | } 32 | } 33 | 34 | return false 35 | } 36 | 37 | func main() { 38 | primes := []int{1, 2} 39 | for i := 3; i < math.MaxInt64; i += 2 { 40 | if isPrime(i) { 41 | primes = append(primes, i) 42 | } 43 | 44 | if !isValidGoldbachConjecture(i, primes) { 45 | fmt.Println(i) 46 | return 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /Problem_47_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "math" 6 | ) 7 | 8 | // https://projecteuler.net/problem=47 9 | 10 | func isPrime(n int) bool { 11 | sqrt := int(math.Sqrt(float64(n))) + 1 12 | for i := 2; i < sqrt; i++ { 13 | if n%i == 0 { 14 | return false 15 | } 16 | } 17 | 18 | return true 19 | } 20 | 21 | func hasNConsecutivePrimes(number int, primes []int, n int) bool { 22 | count := 0 23 | for _, prime := range primes { 24 | if number%prime == 0 { 25 | count += 1 26 | } 27 | } 28 | 29 | return count == n 30 | } 31 | 32 | func main() { 33 | primes := []int{2} 34 | count := 0 35 | distinctFactors := 4 36 | for i := 3; i < math.MaxInt64; i += 1 { 37 | if isPrime(i) { 38 | primes = append(primes, i) 39 | } 40 | 41 | if hasNConsecutivePrimes(i, primes, distinctFactors) { 42 | count += 1 43 | } else { 44 | count = 0 45 | } 46 | 47 | if count == distinctFactors { 48 | fmt.Println(i - distinctFactors + 1) 49 | break 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /Problem_48_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | "math/big" 7 | ) 8 | 9 | // https://projecteuler.net/problem=48 10 | 11 | func main() { 12 | maxNumPtr := flag.Int("number", 1000, "Integer for the max range") 13 | flag.Parse() 14 | 15 | sum := big.NewInt(0) 16 | for i := 1; i <= *maxNumPtr; i++ { 17 | fmt.Println(i) 18 | 19 | val := big.NewInt(int64(i)) 20 | exp := val.Exp(val, val, big.NewInt(0)) 21 | sum.Add(sum, exp) 22 | } 23 | 24 | sumAsString := sum.String() 25 | fmt.Println(sumAsString[len(sumAsString)-10:]) 26 | } 27 | -------------------------------------------------------------------------------- /Problem_49_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "math" 6 | "sort" 7 | "strconv" 8 | ) 9 | 10 | // https://projecteuler.net/problem=49 11 | 12 | func isPrime(n int) bool { 13 | sqrt := int(math.Sqrt(float64(n))) + 1 14 | for i := 2; i < sqrt; i++ { 15 | if n%i == 0 { 16 | return false 17 | } 18 | } 19 | 20 | return true 21 | } 22 | 23 | func rotateDigit(n int) int { 24 | remainder := n - (10 * (n / 10)) 25 | power := float64(len(strconv.Itoa(n))) - 1 26 | 27 | return (remainder * int(math.Pow(10, power))) + (n / 10) 28 | } 29 | 30 | func getCircularPrimes(n int) []int { 31 | newDigit := rotateDigit(n) 32 | values := []int{} 33 | count := 0 34 | 35 | for count != int(math.Log10(float64(n))+1) { 36 | newDigit = rotateDigit(newDigit) 37 | if newDigit < 1000 { 38 | return values 39 | } 40 | values = append(values, newDigit) 41 | count += 1 42 | } 43 | 44 | return values 45 | } 46 | 47 | func getMinimumValue(v []int) string { 48 | min := math.MaxInt32 49 | for _, v := range v { 50 | if v < min { 51 | min = v 52 | } 53 | } 54 | 55 | key := []rune(strconv.Itoa(min)) 56 | sort.Slice(key, func(i int, j int) bool { return key[i] < key[j] }) 57 | 58 | return string(key) 59 | } 60 | 61 | func dedup(v []int) []int { 62 | state := make(map[int]bool) 63 | var newV []int 64 | for _, k := range v { 65 | if _, ok := state[k]; ok { 66 | continue 67 | } 68 | state[k] = true 69 | newV = append(newV, k) 70 | } 71 | 72 | sort.Ints(newV) 73 | return newV 74 | } 75 | 76 | func main() { 77 | values := map[string][]int{} 78 | for i := 1000; i < 10000; i++ { 79 | if !isPrime(i) { 80 | continue 81 | } 82 | 83 | results := getCircularPrimes(i) 84 | sortingKey := getMinimumValue(results) 85 | 86 | if _, ok := values[sortingKey]; !ok { 87 | values[sortingKey] = []int{} 88 | } 89 | 90 | for _, value := range results { 91 | if !isPrime(value) { 92 | continue 93 | } 94 | values[sortingKey] = append(values[sortingKey], value) 95 | } 96 | values[sortingKey] = dedup(values[sortingKey]) 97 | } 98 | 99 | for _, v := range values { 100 | diff := map[int][]int{} 101 | if len(v) < 3 { 102 | continue 103 | } 104 | for i, value := range v { 105 | for _, j := range v[i+1:] { 106 | key := j - value 107 | if _, ok := diff[key]; !ok { 108 | diff[key] = []int{} 109 | } 110 | diff[key] = append(diff[key], []int{j, value}...) 111 | diff[key] = dedup(diff[key]) 112 | } 113 | } 114 | for k, v := range diff { 115 | sort.Ints(v) 116 | if len(v) == 3 { 117 | fmt.Println(k, v) 118 | } 119 | } 120 | } 121 | } 122 | -------------------------------------------------------------------------------- /Problem_4_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | // https://projecteuler.net/problem=4 4 | 5 | // 998001 999 x 999 6 | 7 | // 996699 8 | 9 | // 100000 100 x 100 10 | 11 | 12 | import ( 13 | "math" 14 | "fmt" 15 | ) 16 | 17 | func reverseNumber(n int) int{ 18 | reverse := 0 19 | for n > 0 { 20 | lastDigit := n % 10 21 | reverse = (reverse * 10) + lastDigit 22 | n = n / 10 23 | } 24 | return reverse 25 | } 26 | 27 | 28 | func getLargestPalindrome() int{ 29 | maxPalindrome := -math.MaxInt64 30 | for i :=1000; i > 0; i-- { 31 | for j := 1000; j > 0; j-- { 32 | product := i * j 33 | if product == reverseNumber(product) && product > maxPalindrome { 34 | maxPalindrome = product 35 | } 36 | } 37 | } 38 | return maxPalindrome 39 | } 40 | 41 | 42 | func main(){ 43 | fmt.Println(getLargestPalindrome()) 44 | } 45 | -------------------------------------------------------------------------------- /Problem_50_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | "math" 7 | ) 8 | 9 | // https://projecteuler.net/problem=50 10 | 11 | func isPrime(n int) bool { 12 | sqrt := int(math.Sqrt(float64(n))) + 1 13 | for i := 2; i < sqrt; i++ { 14 | if n%i == 0 { 15 | return false 16 | } 17 | } 18 | 19 | return true 20 | } 21 | 22 | func main() { 23 | window := flag.Int("window", 1_000_000, "Max number to sum to") 24 | flag.Parse() 25 | 26 | //terms := 0 27 | primes := []int{} 28 | primesSum := []int{0} 29 | for i := 2; i < *window; i++ { 30 | if isPrime(i) { 31 | primes = append(primes, i) 32 | primesSum = append(primesSum, i+primesSum[len(primesSum)-1]) 33 | } 34 | } 35 | 36 | maxSum := math.MinInt 37 | maxI, maxJ := 0, 0 38 | terms := 0 39 | 40 | for i := 0; i < len(primes); i++ { 41 | for j := 0; j < len(primesSum); j++ { 42 | if primesSum[j] == 0 { 43 | continue 44 | } 45 | 46 | if primesSum[j] > 0 && primesSum[j] < *window && isPrime(primesSum[j]) && j-i > terms { 47 | fmt.Println(i, j, primesSum[j]) 48 | maxI = i 49 | maxJ = j 50 | terms = j - i 51 | maxSum = primesSum[j] 52 | } 53 | 54 | primesSum[j] -= primes[i] 55 | } 56 | } 57 | 58 | fmt.Println("------------------") 59 | for i := maxI; i < maxJ; i++ { 60 | fmt.Print(primes[i], " ") 61 | } 62 | fmt.Println() 63 | fmt.Println(maxJ-maxI, maxSum) 64 | } 65 | -------------------------------------------------------------------------------- /Problem_51_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | "math" 7 | "math/bits" 8 | "strconv" 9 | ) 10 | 11 | // https://projecteuler.net/problem=51 12 | 13 | func isPrime(n int) bool { 14 | i := 2 15 | for i <= int(math.Sqrt(float64(n))) { 16 | if n%i == 0 { 17 | return false 18 | } 19 | i++ 20 | } 21 | 22 | return true 23 | } 24 | 25 | func getValue(digits []int) int { 26 | value := 0 27 | for i := 0; i < len(digits); i++ { 28 | value += int(math.Pow(10, float64(i))) * digits[len(digits)-i-1] 29 | } 30 | 31 | return value 32 | } 33 | 34 | func breakNumber(n int) []int { 35 | result := []int{} 36 | for n > 0 { 37 | result = append([]int{n % 10}, result...) 38 | n /= 10 39 | } 40 | 41 | return result 42 | } 43 | 44 | // Combinations returns combinations of n elements for a given generic array. 45 | // For n < 1, it equals to All and returns all combinations. 46 | func Combinations[T any](set []T, n int) (subsets [][]T) { 47 | length := uint(len(set)) 48 | 49 | if n > len(set) { 50 | n = len(set) 51 | } 52 | 53 | // Go through all possible combinations of objects 54 | // from 1 (only first object in subset) to 2^length (all objects in subset) 55 | for subsetBits := 1; subsetBits < (1 << length); subsetBits++ { 56 | if n > 0 && bits.OnesCount(uint(subsetBits)) != n { 57 | continue 58 | } 59 | 60 | var subset []T 61 | 62 | for object := uint(0); object < length; object++ { 63 | // checks if object is contained in subset 64 | // by checking if bit 'object' is set in subsetBits 65 | if (subsetBits>>object)&1 == 1 { 66 | // add object to subset 67 | subset = append(subset, set[object]) 68 | } 69 | } 70 | // add subset to subsets 71 | subsets = append(subsets, subset) 72 | } 73 | return subsets 74 | } 75 | 76 | func generateCombinations(numbers []int, combinations int) [][]int { 77 | return Combinations(numbers, combinations) 78 | } 79 | 80 | func getReplacementIndexes(number []int, digit int) []int { 81 | replacementIndexes := []int{} 82 | for i := 0; i < len(number); i++ { 83 | if number[i] == digit { 84 | replacementIndexes = append(replacementIndexes, i) 85 | } 86 | } 87 | 88 | return replacementIndexes 89 | } 90 | 91 | func getNumLength(num int) int { 92 | return len(strconv.Itoa(num)) 93 | } 94 | 95 | func getPrimesFromReplacementIndex(number []int, replacements []int, digit int) []int { 96 | primes := []int{} 97 | for i := 0; i < 10; i++ { 98 | newDigits := make([]int, len(number)) 99 | copy(newDigits, number) 100 | for _, v := range replacements { 101 | newDigits[v] = i 102 | } 103 | 104 | newNumber := getValue(newDigits) 105 | if getNumLength(newNumber) != len(number) { 106 | continue 107 | } 108 | if isPrime(newNumber) { 109 | primes = append(primes, newNumber) 110 | } 111 | } 112 | 113 | return primes 114 | } 115 | 116 | func main() { 117 | window := flag.Int("window", 6, "Number of prime factors to find replacements matching") 118 | flag.Parse() 119 | 120 | for i := 10; i < math.MaxInt64; i++ { 121 | if isPrime(i) { 122 | digits := breakNumber(i) 123 | digitCounts := map[int]int{} 124 | for _, digit := range digits { 125 | digitCounts[digit]++ 126 | } 127 | 128 | for k, v := range digitCounts { 129 | for j := 1; j <= v; j++ { 130 | indexes := getReplacementIndexes(digits, k) 131 | for _, c := range generateCombinations(indexes, j) { 132 | primes := getPrimesFromReplacementIndex(digits, c, k) 133 | if len(primes) == *window { 134 | fmt.Println(primes) 135 | return 136 | } 137 | } 138 | } 139 | } 140 | } 141 | 142 | } 143 | } 144 | -------------------------------------------------------------------------------- /Problem_52_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | "math" 7 | ) 8 | 9 | // https://projecteuler.net/problem=52 10 | 11 | func breakNumber(n int) []int { 12 | result := []int{} 13 | for n > 0 { 14 | result = append([]int{n % 10}, result...) 15 | n /= 10 16 | } 17 | 18 | return result 19 | } 20 | 21 | func isEqual(a map[int]int, b map[int]int) bool { 22 | if len(a) != len(b) { 23 | return false 24 | } 25 | for k1, v1 := range a { 26 | v2, ok := b[k1] 27 | if !ok || v2 != v1 { 28 | return false 29 | } 30 | } 31 | 32 | return true 33 | } 34 | 35 | func getDigitCounts(number int) map[int]int { 36 | digits := breakNumber(number) 37 | digitCounts := map[int]int{} 38 | for _, digit := range digits { 39 | digitCounts[digit]++ 40 | } 41 | 42 | return digitCounts 43 | } 44 | 45 | func isPermutedMultiple(prevDigitCounts map[int]int, window int, number int) bool { 46 | for multiplier := 2; multiplier <= window; multiplier++ { 47 | if !isEqual(prevDigitCounts, getDigitCounts(multiplier*number)) { 48 | return false 49 | } 50 | } 51 | 52 | return true 53 | } 54 | 55 | func main() { 56 | window := flag.Int("window", 6, "Range of multiplier") 57 | flag.Parse() 58 | 59 | for i := 2; i < math.MaxInt64; i++ { 60 | prevDigitCounts := getDigitCounts(i) 61 | if isPermutedMultiple(prevDigitCounts, *window, i) { 62 | fmt.Println(i) 63 | return 64 | } 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /Problem_53_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "math/big" 6 | ) 7 | 8 | // https://projecteuler.net/problem=53 9 | 10 | func factorial(n int) *big.Int { 11 | result := big.NewInt(int64(1)) 12 | 13 | if n == 0 { 14 | return result 15 | } 16 | for i := 1; i <= n; i++ { 17 | result = result.Mul(result, big.NewInt(int64(i))) 18 | } 19 | 20 | return result 21 | } 22 | 23 | func main() { 24 | oneMillion := big.NewInt(1_000_000) 25 | count := 0 26 | factorialMap := make(map[int]*big.Int) 27 | for i := 0; i <= 100; i++ { 28 | factorialMap[i] = factorial(i) 29 | } 30 | 31 | for n := 1; n <= 100; n++ { 32 | for r := 1; r < n; r++ { 33 | nf := big.NewInt(1).Mul(big.NewInt(1), factorialMap[n]) 34 | rf := big.NewInt(1).Mul(big.NewInt(1), factorialMap[r]) 35 | nmrf := big.NewInt(1).Mul(big.NewInt(1), factorialMap[n-r]) 36 | if nf.Div(nf, rf.Mul(rf, nmrf)).Cmp(oneMillion) > 0 { 37 | count += 1 38 | } 39 | } 40 | } 41 | 42 | fmt.Println(count) 43 | } 44 | -------------------------------------------------------------------------------- /Problem_54_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "math" 6 | "os" 7 | "sort" 8 | "strings" 9 | ) 10 | 11 | // https://projecteuler.net/problem=54 12 | 13 | var ( 14 | order = []string{"2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K", "A"} 15 | ) 16 | 17 | func index(card string) int { 18 | for i, c := range order { 19 | if c == card { 20 | return i 21 | } 22 | } 23 | 24 | panic("Not found") 25 | } 26 | 27 | func sortCards(cards []string) { 28 | sort.Slice(cards, func(i, j int) bool { 29 | return index(cards[i]) < index(cards[j]) 30 | }) 31 | } 32 | 33 | func formatHands(hands []string) map[string][]string { 34 | cards := map[string][]string{} 35 | for _, hand := range hands { 36 | suits := strings.Split(hand, "") 37 | num := suits[0] 38 | suit := suits[1] 39 | if _, ok := cards[suit]; !ok { 40 | cards[suit] = []string{} 41 | } 42 | cards[suit] = append(cards[suit], num) 43 | } 44 | 45 | for _, c := range cards { 46 | sortCards(c) 47 | } 48 | 49 | return cards 50 | } 51 | 52 | func fullHouse(hands []string) int { 53 | answer := nOfAKind(hands, 3, 1) 54 | verifier := nOfAKind(hands, 2, 1) 55 | if verifier*answer == 0 { 56 | return 0 57 | } 58 | 59 | return answer 60 | } 61 | 62 | func getCardCounts(cards map[string][]string) map[string]int { 63 | cardCounts := map[string]int{} 64 | for _, card := range cards { 65 | for _, suit := range card { 66 | cardCounts[suit]++ 67 | } 68 | } 69 | 70 | return cardCounts 71 | } 72 | 73 | func nOfAKind(hands []string, n int, occurrences int) int { 74 | cards := formatHands(hands) 75 | cardCounts := getCardCounts(cards) 76 | value := float64(math.MinInt64) 77 | 78 | for k, c := range cardCounts { 79 | if c == n { 80 | occurrences -= 1 81 | value = math.Max(float64(index(k)), value) 82 | } 83 | } 84 | 85 | if occurrences == 0 { 86 | return int(value) 87 | } 88 | 89 | return 0 90 | } 91 | 92 | func fourOfAKind(hands []string) int { 93 | return nOfAKind(hands, 4, 1) 94 | } 95 | 96 | func threeOfAKind(hands []string) int { 97 | return nOfAKind(hands, 3, 1) 98 | } 99 | 100 | func twoPairs(hands []string) int { 101 | return nOfAKind(hands, 2, 2) 102 | } 103 | 104 | func onePair(hands []string) int { 105 | return nOfAKind(hands, 2, 1) 106 | } 107 | 108 | func highestCard(hands []string) int { 109 | cards := formatHands(hands) 110 | start := index("2") 111 | cardCounts := getCardCounts(cards) 112 | for _, card := range cards { 113 | for _, suit := range card { 114 | if cardCounts[suit] > 1 { 115 | continue 116 | } 117 | if index(suit) > start { 118 | start = index(suit) 119 | } 120 | } 121 | } 122 | 123 | return start 124 | } 125 | 126 | func straight(hands []string) int { 127 | cards := formatHands(hands) 128 | cardCounts := getCardCounts(cards) 129 | hasTwoAndAce := (cardCounts["A"] * cardCounts["2"]) != 0 130 | prevCard := "" 131 | for _, card := range order { 132 | if _, ok := cardCounts[card]; ok { 133 | if prevCard == "" { 134 | prevCard = card 135 | continue 136 | } 137 | if card == "A" && hasTwoAndAce { 138 | return 1 139 | } 140 | if index(card)-index(prevCard) != 1 { 141 | return 0 142 | } 143 | prevCard = card 144 | } 145 | } 146 | 147 | return highestCard(hands) 148 | } 149 | 150 | func flush(hands []string) int { 151 | cards := formatHands(hands) 152 | 153 | if len(cards) != 1 { 154 | return 0 155 | } 156 | 157 | return highestCard(hands) 158 | } 159 | 160 | func straightFlush(hands []string) int { 161 | cards := formatHands(hands) 162 | if len(cards) != 1 { 163 | return 0 164 | } 165 | 166 | for _, card := range cards { 167 | firstIndex := index(card[0]) 168 | for i := 1; i < len(card); i++ { 169 | if index(card[i])-firstIndex != 1 { 170 | return 0 171 | } 172 | firstIndex = index(card[i]) 173 | } 174 | } 175 | 176 | return highestCard(hands) 177 | } 178 | 179 | func isRoyalFlush(hands []string) int { 180 | cards := formatHands(hands) 181 | firstIndex := index("T") 182 | if len(cards) != 1 { 183 | return 0 184 | } 185 | 186 | for _, card := range cards { 187 | for _, c := range card { 188 | if index(c) != firstIndex { 189 | return 0 190 | } 191 | firstIndex += 1 192 | } 193 | } 194 | 195 | return 1 196 | } 197 | 198 | func winningHand(p1 []string, p2 []string) bool { 199 | p1Stats := []int{isRoyalFlush(p1), straightFlush(p1), fourOfAKind(p1), fullHouse(p1), flush(p1), straight(p1), threeOfAKind(p1), twoPairs(p1), onePair(p1), highestCard(p1)} 200 | p2Stats := []int{isRoyalFlush(p2), straightFlush(p2), fourOfAKind(p2), fullHouse(p2), flush(p2), straight(p2), threeOfAKind(p2), twoPairs(p2), onePair(p2), highestCard(p2)} 201 | 202 | fmt.Println(p1Stats) 203 | fmt.Println(p2Stats) 204 | 205 | for i := 0; i <= len(p1Stats); i++ { 206 | if p1Stats[i] == 0 && p2Stats[i] == 0 || p1Stats[i] == p2Stats[i] { 207 | continue 208 | } 209 | return p1Stats[i] > p2Stats[i] 210 | } 211 | 212 | return false 213 | } 214 | 215 | func main() { 216 | content, err := os.ReadFile("poker.txt") 217 | if err != nil { 218 | panic(err) 219 | } 220 | 221 | count := 0 222 | lines := strings.Split(string(content), "\n") 223 | for _, line := range lines { 224 | fmt.Println(line) 225 | options := strings.Split(line, " ") 226 | p1 := options[:5] 227 | p2 := options[5:] 228 | 229 | if winningHand(p1, p2) { 230 | fmt.Println("p1") 231 | count += 1 232 | } else { 233 | fmt.Println("p2") 234 | } 235 | } 236 | 237 | fmt.Println("--------------") 238 | fmt.Println(count) 239 | } 240 | -------------------------------------------------------------------------------- /Problem_55_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | "math/big" 7 | ) 8 | 9 | // https://projecteuler.net/problem=55 10 | 11 | func reverseNumber(n *big.Int) *big.Int { 12 | reverse := big.NewInt(0) 13 | ten := big.NewInt(10) 14 | 15 | newN := big.NewInt(0) 16 | newN.Add(newN, n) 17 | 18 | for newN.Cmp(big.NewInt(0)) > 0 { 19 | lastDigit := big.NewInt(1).Mod(newN, ten) 20 | reverse.Mul(reverse, ten).Add(reverse, lastDigit) 21 | newN = newN.Div(newN, ten) 22 | } 23 | 24 | return reverse 25 | } 26 | 27 | func main() { 28 | window := flag.Int("window", 10_000, "Range to find the longest lychrel number") 29 | flag.Parse() 30 | 31 | count := 0 32 | 33 | for i := 0; i < *window; i++ { 34 | number := big.NewInt(int64(i)) 35 | maxIterations := 50 36 | 37 | for maxIterations > 0 { 38 | reversedNumber := reverseNumber(number) 39 | number.Add(number, reversedNumber) 40 | maxIterations-- 41 | if number.Cmp(reverseNumber(number)) == 0 { 42 | break 43 | } 44 | } 45 | 46 | if maxIterations == 0 { 47 | fmt.Println(i) 48 | count += 1 49 | } 50 | } 51 | 52 | fmt.Println("---------------") 53 | fmt.Println(count) 54 | } 55 | -------------------------------------------------------------------------------- /Problem_56_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | "math" 7 | "math/big" 8 | ) 9 | 10 | // https://projecteuler.net/problem=56 11 | 12 | func main() { 13 | window := flag.Int("window", 100, "Range to find the longest lychrel number") 14 | flag.Parse() 15 | 16 | ten := big.NewInt(10) 17 | maxSum := math.MinInt64 18 | 19 | for i := 1; i < *window; i++ { 20 | for j := 1; j < *window; j++ { 21 | a := big.NewInt(int64(i)) 22 | b := big.NewInt(int64(j)) 23 | c := a.Exp(a, b, nil) 24 | sum := 0 25 | 26 | for c.Cmp(big.NewInt(0)) != 0 { 27 | sum += int(big.NewInt(1).Mod(c, ten).Int64()) 28 | c.Div(c, ten) 29 | } 30 | 31 | if sum > maxSum { 32 | fmt.Println(i, j, sum) 33 | maxSum = sum 34 | } 35 | } 36 | } 37 | 38 | fmt.Println("------------------") 39 | fmt.Println(maxSum) 40 | 41 | } 42 | -------------------------------------------------------------------------------- /Problem_57_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | "math/big" 7 | ) 8 | 9 | // https://projecteuler.net/problem=57 10 | 11 | func main() { 12 | window := flag.Int("window", 1_000, "Range to find the longest lychrel number") 13 | flag.Parse() 14 | 15 | count := 0 16 | 17 | numerator, denominator := big.NewInt(3), big.NewInt(2) 18 | for i := 0; i < *window; i++ { 19 | oldNumerator := big.NewInt(1) 20 | oldNumerator.Mul(oldNumerator, numerator) 21 | 22 | oldDenominator := big.NewInt(1) 23 | oldDenominator.Mul(oldDenominator, denominator) 24 | 25 | numerator.Add(numerator, oldDenominator.Mul(oldDenominator, big.NewInt(2))) 26 | denominator.Add(denominator, oldNumerator) 27 | if len(numerator.String()) != len(denominator.String()) { 28 | fmt.Println(numerator, denominator) 29 | count += 1 30 | } 31 | } 32 | 33 | fmt.Println("-----------") 34 | fmt.Println(count) 35 | } 36 | -------------------------------------------------------------------------------- /Problem_58_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | "math" 7 | ) 8 | 9 | // https://projecteuler.net/problem=58 10 | 11 | func isPrime(n int) bool { 12 | i := 2 13 | for i <= int(math.Sqrt(float64(n))) { 14 | if n%i == 0 { 15 | return false 16 | } 17 | i++ 18 | } 19 | return true 20 | } 21 | 22 | func main() { 23 | window := flag.Float64("window", 0.1, "Ratio of prime diagonals to stop at") 24 | flag.Parse() 25 | 26 | count := 0 27 | for i := 3; i < math.MaxInt64; i += 2 { 28 | leftBottomDiagonal := i * i 29 | rightTopDiagonal := leftBottomDiagonal - (i-1)*2 30 | rightBottomDiagonal := leftBottomDiagonal - (i - 1) 31 | leftTopDiagonal := ((i - 2) * (i - 2)) + (i - 1) 32 | for _, number := range []int{leftBottomDiagonal, leftTopDiagonal, rightTopDiagonal, rightBottomDiagonal} { 33 | if isPrime(number) { 34 | count += 1 35 | } 36 | } 37 | 38 | numberOfPrimeDiagonals := float64(2*i - 1) 39 | if float64(count)/numberOfPrimeDiagonals < *window { 40 | fmt.Println(i, count, numberOfPrimeDiagonals) 41 | return 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /Problem_59_Euler/0059_cipher.txt: -------------------------------------------------------------------------------- 1 | 36,22,80,0,0,4,23,25,19,17,88,4,4,19,21,11,88,22,23,23,29,69,12,24,0,88,25,11,12,2,10,28,5,6,12,25,10,22,80,10,30,80,10,22,21,69,23,22,69,61,5,9,29,2,66,11,80,8,23,3,17,88,19,0,20,21,7,10,17,17,29,20,69,8,17,21,29,2,22,84,80,71,60,21,69,11,5,8,21,25,22,88,3,0,10,25,0,10,5,8,88,2,0,27,25,21,10,31,6,25,2,16,21,82,69,35,63,11,88,4,13,29,80,22,13,29,22,88,31,3,88,3,0,10,25,0,11,80,10,30,80,23,29,19,12,8,2,10,27,17,9,11,45,95,88,57,69,16,17,19,29,80,23,29,19,0,22,4,9,1,80,3,23,5,11,28,92,69,9,5,12,12,21,69,13,30,0,0,0,0,27,4,0,28,28,28,84,80,4,22,80,0,20,21,2,25,30,17,88,21,29,8,2,0,11,3,12,23,30,69,30,31,23,88,4,13,29,80,0,22,4,12,10,21,69,11,5,8,88,31,3,88,4,13,17,3,69,11,21,23,17,21,22,88,65,69,83,80,84,87,68,69,83,80,84,87,73,69,83,80,84,87,65,83,88,91,69,29,4,6,86,92,69,15,24,12,27,24,69,28,21,21,29,30,1,11,80,10,22,80,17,16,21,69,9,5,4,28,2,4,12,5,23,29,80,10,30,80,17,16,21,69,27,25,23,27,28,0,84,80,22,23,80,17,16,17,17,88,25,3,88,4,13,29,80,17,10,5,0,88,3,16,21,80,10,30,80,17,16,25,22,88,3,0,10,25,0,11,80,12,11,80,10,26,4,4,17,30,0,28,92,69,30,2,10,21,80,12,12,80,4,12,80,10,22,19,0,88,4,13,29,80,20,13,17,1,10,17,17,13,2,0,88,31,3,88,4,13,29,80,6,17,2,6,20,21,69,30,31,9,20,31,18,11,94,69,54,17,8,29,28,28,84,80,44,88,24,4,14,21,69,30,31,16,22,20,69,12,24,4,12,80,17,16,21,69,11,5,8,88,31,3,88,4,13,17,3,69,11,21,23,17,21,22,88,25,22,88,17,69,11,25,29,12,24,69,8,17,23,12,80,10,30,80,17,16,21,69,11,1,16,25,2,0,88,31,3,88,4,13,29,80,21,29,2,12,21,21,17,29,2,69,23,22,69,12,24,0,88,19,12,10,19,9,29,80,18,16,31,22,29,80,1,17,17,8,29,4,0,10,80,12,11,80,84,67,80,10,10,80,7,1,80,21,13,4,17,17,30,2,88,4,13,29,80,22,13,29,69,23,22,69,12,24,12,11,80,22,29,2,12,29,3,69,29,1,16,25,28,69,12,31,69,11,92,69,17,4,69,16,17,22,88,4,13,29,80,23,25,4,12,23,80,22,9,2,17,80,70,76,88,29,16,20,4,12,8,28,12,29,20,69,26,9,69,11,80,17,23,80,84,88,31,3,88,4,13,29,80,21,29,2,12,21,21,17,29,2,69,12,31,69,12,24,0,88,20,12,25,29,0,12,21,23,86,80,44,88,7,12,20,28,69,11,31,10,22,80,22,16,31,18,88,4,13,25,4,69,12,24,0,88,3,16,21,80,10,30,80,17,16,25,22,88,3,0,10,25,0,11,80,17,23,80,7,29,80,4,8,0,23,23,8,12,21,17,17,29,28,28,88,65,75,78,68,81,65,67,81,72,70,83,64,68,87,74,70,81,75,70,81,67,80,4,22,20,69,30,2,10,21,80,8,13,28,17,17,0,9,1,25,11,31,80,17,16,25,22,88,30,16,21,18,0,10,80,7,1,80,22,17,8,73,88,17,11,28,80,17,16,21,11,88,4,4,19,25,11,31,80,17,16,21,69,11,1,16,25,2,0,88,2,10,23,4,73,88,4,13,29,80,11,13,29,7,29,2,69,75,94,84,76,65,80,65,66,83,77,67,80,64,73,82,65,67,87,75,72,69,17,3,69,17,30,1,29,21,1,88,0,23,23,20,16,27,21,1,84,80,18,16,25,6,16,80,0,0,0,23,29,3,22,29,3,69,12,24,0,88,0,0,10,25,8,29,4,0,10,80,10,30,80,4,88,19,12,10,19,9,29,80,18,16,31,22,29,80,1,17,17,8,29,4,0,10,80,12,11,80,84,86,80,35,23,28,9,23,7,12,22,23,69,25,23,4,17,30,69,12,24,0,88,3,4,21,21,69,11,4,0,8,3,69,26,9,69,15,24,12,27,24,69,49,80,13,25,20,69,25,2,23,17,6,0,28,80,4,12,80,17,16,25,22,88,3,16,21,92,69,49,80,13,25,6,0,88,20,12,11,19,10,14,21,23,29,20,69,12,24,4,12,80,17,16,21,69,11,5,8,88,31,3,88,4,13,29,80,22,29,2,12,29,3,69,73,80,78,88,65,74,73,70,69,83,80,84,87,72,84,88,91,69,73,95,87,77,70,69,83,80,84,87,70,87,77,80,78,88,21,17,27,94,69,25,28,22,23,80,1,29,0,0,22,20,22,88,31,11,88,4,13,29,80,20,13,17,1,10,17,17,13,2,0,88,31,3,88,4,13,29,80,6,17,2,6,20,21,75,88,62,4,21,21,9,1,92,69,12,24,0,88,3,16,21,80,10,30,80,17,16,25,22,88,29,16,20,4,12,8,28,12,29,20,69,26,9,69,65,64,69,31,25,19,29,3,69,12,24,0,88,18,12,9,5,4,28,2,4,12,21,69,80,22,10,13,2,17,16,80,21,23,7,0,10,89,69,23,22,69,12,24,0,88,19,12,10,19,16,21,22,0,10,21,11,27,21,69,23,22,69,12,24,0,88,0,0,10,25,8,29,4,0,10,80,10,30,80,4,88,19,12,10,19,9,29,80,18,16,31,22,29,80,1,17,17,8,29,4,0,10,80,12,11,80,84,86,80,36,22,20,69,26,9,69,11,25,8,17,28,4,10,80,23,29,17,22,23,30,12,22,23,69,49,80,13,25,6,0,88,28,12,19,21,18,17,3,0,88,18,0,29,30,69,25,18,9,29,80,17,23,80,1,29,4,0,10,29,12,22,21,69,12,24,0,88,3,16,21,3,69,23,22,69,12,24,0,88,3,16,26,3,0,9,5,0,22,4,69,11,21,23,17,21,22,88,25,11,88,7,13,17,19,13,88,4,13,29,80,0,0,0,10,22,21,11,12,3,69,25,2,0,88,21,19,29,30,69,22,5,8,26,21,23,11,94 -------------------------------------------------------------------------------- /Problem_59_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | "os" 7 | "strconv" 8 | "strings" 9 | ) 10 | 11 | // https://projecteuler.net/problem=59 12 | 13 | func xor(a, b byte) byte { 14 | return a ^ b 15 | } 16 | 17 | func decrypt(text []byte, key []byte) []byte { 18 | var result []byte 19 | for i := 0; i < len(text); i++ { 20 | result = append(result, xor(text[i], key[i%len(key)])) 21 | } 22 | 23 | return result 24 | } 25 | 26 | func generateCombinations(numbers []string) [][]string { 27 | var result [][]string 28 | for i := 0; i < len(numbers); i++ { 29 | for j := 0; j < len(numbers); j++ { 30 | for k := 0; k < len(numbers); k++ { 31 | result = append(result, []string{numbers[i], numbers[j], numbers[k]}) 32 | } 33 | } 34 | } 35 | 36 | return result 37 | } 38 | 39 | func main() { 40 | fileName := flag.String("file", "0059_cipher.txt", "File to read integers from") 41 | flag.Parse() 42 | 43 | letters := []string{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"} 44 | 45 | content, err := os.ReadFile(*fileName) 46 | if err != nil { 47 | panic(err) 48 | } 49 | 50 | var numbers []byte 51 | for _, line := range strings.Split(string(content), ",") { 52 | number, err := strconv.Atoi(line) 53 | if err != nil { 54 | panic(err) 55 | } 56 | numbers = append(numbers, byte(number)) 57 | } 58 | 59 | text, maxCount := "", 0 60 | for _, combination := range generateCombinations(letters) { 61 | var key []byte 62 | for _, c := range combination { 63 | key = append(key, []byte(c)[0]) 64 | } 65 | 66 | result := decrypt(numbers, key) 67 | count := len(strings.Split(string(result), " ")) 68 | 69 | if count > maxCount { 70 | text = string(result) 71 | maxCount = count 72 | fmt.Println(string(result), string(key), count) 73 | } 74 | } 75 | 76 | fmt.Println("------------") 77 | fmt.Println(text, maxCount) 78 | 79 | asciiSum := 0 80 | for _, c := range text { 81 | asciiSum += int(c) 82 | } 83 | 84 | fmt.Println(asciiSum) 85 | } 86 | -------------------------------------------------------------------------------- /Problem_5_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | 4 | import ( 5 | "fmt" 6 | "flag" 7 | "math" 8 | ) 9 | 10 | 11 | // https://projecteuler.net/problem=5 12 | 13 | func isPrime(n int) bool{ 14 | i := 2 15 | for i <= int(math.Sqrt(float64(n))) { 16 | if n % i == 0 { 17 | return false 18 | } 19 | i++ 20 | } 21 | return true 22 | } 23 | 24 | 25 | func smallestPositiveDivisibleNumber(nMax int) int { 26 | result := 1 27 | n := 2 28 | nMax-- 29 | for n <= nMax { 30 | if isPrime(n) { 31 | fmt.Println("Is Prime ", n) 32 | invRoot := math.Pow(float64(n), -1) 33 | invPower := math.Floor(math.Pow(float64(nMax), invRoot)) 34 | maxPower := math.Pow(float64(n), invPower) 35 | fmt.Println("Largest multiple ", maxPower) 36 | result = result * int(maxPower) 37 | } 38 | n++ 39 | } 40 | return result 41 | } 42 | 43 | 44 | func main(){ 45 | maxNumPtr := flag.Int("number", 20, "Integer for the max range") 46 | flag.Parse() 47 | fmt.Println("Smallest divisible product ", smallestPositiveDivisibleNumber(*maxNumPtr)) 48 | } 49 | -------------------------------------------------------------------------------- /Problem_60_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | "math" 7 | "sync" 8 | ) 9 | 10 | // https://projecteuler.net/problem=60 11 | 12 | func isPrime(n int) bool { 13 | i := 2 14 | if n == 0 || n == 1 { 15 | return false 16 | } 17 | for i <= int(math.Sqrt(float64(n))) { 18 | if n%i == 0 { 19 | return false 20 | } 21 | i++ 22 | } 23 | 24 | return true 25 | } 26 | 27 | func getValue(digits []int) int { 28 | value := 0 29 | power := 0 30 | for i := 0; i < len(digits); i++ { 31 | number := float64(digits[len(digits)-i-1]) 32 | value += int(math.Pow(10, float64(power)) * number) 33 | power += int(math.Floor(math.Log10(number)) + 1) 34 | } 35 | 36 | return value 37 | } 38 | 39 | func isPrimePair(a, b int) bool { 40 | for _, number := range [][]int{{a, b}, {b, a}} { 41 | if !isPrime(getValue(number)) { 42 | return false 43 | } 44 | } 45 | 46 | return true 47 | } 48 | 49 | func sum(n []int) int { 50 | result := 0 51 | for _, n := range n { 52 | result += n 53 | } 54 | 55 | return result 56 | } 57 | 58 | func getCombinations(arr, rest []int, n int, result [][]int) [][]int { 59 | if n == 0 { 60 | return [][]int{arr} 61 | } else { 62 | for i, k := range rest { 63 | result = append(result, getCombinations(append([]int{k}, arr...), rest[i+1:], n-1, [][]int{})...) 64 | } 65 | } 66 | 67 | return result 68 | } 69 | 70 | func processResult(combChan, resultChan chan []int, primes []int, wg *sync.WaitGroup) { 71 | for comb := range combChan { 72 | for _, p := range primes { 73 | if comb[0] >= p { 74 | continue 75 | } 76 | isValid := true 77 | newList := append([]int{p}, comb...) 78 | for _, d := range getCombinations([]int{}, newList, 2, [][]int{}) { 79 | if !isPrimePair(d[0], d[1]) { 80 | isValid = false 81 | break 82 | } 83 | } 84 | if isValid { 85 | resultChan <- newList 86 | } 87 | } 88 | } 89 | wg.Done() 90 | } 91 | 92 | func main() { 93 | window := flag.Int("window", 4, "Number of prime factors to find replacements matching") 94 | flag.Parse() 95 | 96 | for primeWindow := 1000; primeWindow < math.MaxInt64; primeWindow += 1000 { 97 | fmt.Println("Prime window:", primeWindow) 98 | var primes []int 99 | for i := 1; i < primeWindow; i++ { 100 | if isPrime(i) { 101 | primes = append(primes, i) 102 | } 103 | } 104 | 105 | fmt.Println(len(primes), *window) 106 | 107 | combinations := getCombinations([]int{}, primes, 5, [][]int{}) 108 | fmt.Println(len(combinations), *window) 109 | fmt.Println("-------------") 110 | 111 | //for i := 3; i < *window; i++ { 112 | // var newCombinations [][]int 113 | // for _, comb := range combinations { 114 | // for _, p := range primes { 115 | // if comb[0] >= p { 116 | // continue 117 | // } 118 | // isValid := true 119 | // newList := append([]int{p}, comb...) 120 | // for _, d := range getCombinations([]int{}, newList, 2, [][]int{}) { 121 | // if !isPrimePair(d[0], d[1]) { 122 | // isValid = false 123 | // break 124 | // } 125 | // } 126 | // if isValid { 127 | // newCombinations = append(newCombinations, newList) 128 | // if i == *window { 129 | // fmt.Println("-------------") 130 | // fmt.Println(newList, sum(newList)) 131 | // return 132 | // } 133 | // } 134 | // } 135 | // } 136 | //} 137 | 138 | for i := 3; i < *window+1; i++ { 139 | var newCombinations [][]int 140 | combChan := make(chan []int) 141 | resultChan := make(chan []int) 142 | wg := &sync.WaitGroup{} 143 | for k := 0; k < 15; k++ { 144 | wg.Add(1) 145 | go processResult(combChan, resultChan, primes, wg) 146 | } 147 | go func() { 148 | for _, k := range combinations { 149 | combChan <- k 150 | } 151 | close(combChan) 152 | wg.Wait() 153 | close(resultChan) 154 | }() 155 | 156 | for newList := range resultChan { 157 | newCombinations = append(newCombinations, newList) 158 | if i == *window { 159 | fmt.Println("-------------") 160 | fmt.Println(newList, sum(newList)) 161 | return 162 | } 163 | } 164 | combinations = newCombinations 165 | fmt.Println(len(newCombinations), i) 166 | } 167 | } 168 | } 169 | -------------------------------------------------------------------------------- /Problem_61_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "math" 6 | "os" 7 | ) 8 | 9 | // https://projecteuler.net/problem=45 10 | 11 | func getQuadraticRoots(a, b, c float64) (float64, float64) { 12 | firstRoot := (-b + math.Sqrt(math.Pow(b, 2)-(4*a*c))) / (2 * a) 13 | secondRoot := (-b - math.Sqrt(math.Pow(b, 2)-(4*a*c))) / (2 * a) 14 | 15 | return firstRoot, secondRoot 16 | } 17 | 18 | func isValidRoot(ft, st float64) bool { 19 | for _, roots := range [][]float64{{ft, st}} { 20 | for _, root := range roots { 21 | if root > 0 && math.Floor(root) == root { 22 | return true 23 | } 24 | } 25 | } 26 | 27 | return false 28 | } 29 | 30 | func firstAndLastTwo(i int) (int, int) { 31 | return i / 100, i % 100 32 | } 33 | 34 | func sum(n []int) int { 35 | result := 0 36 | for _, n := range n { 37 | result += n 38 | } 39 | 40 | return result 41 | } 42 | 43 | func has(haystack []int, needle int) bool { 44 | for _, n := range haystack { 45 | if n == needle { 46 | return true 47 | } 48 | } 49 | 50 | return false 51 | } 52 | 53 | func filter(s string, haystack []string) []string { 54 | result := []string{} 55 | for _, hay := range haystack { 56 | if hay != s { 57 | result = append(result, hay) 58 | } 59 | } 60 | 61 | return result 62 | } 63 | 64 | func backtrack(shapes []string, digits []int, order []string, sets map[string][][]int) { 65 | if len(shapes) == 0 { 66 | first, _ := firstAndLastTwo(digits[0]) 67 | _, lastD := firstAndLastTwo(digits[len(digits)-1]) 68 | if lastD == first { 69 | fmt.Println("---------------") 70 | fmt.Println(digits, order) 71 | fmt.Println(sum(digits)) 72 | // There is only one solution, so we can exit on the first version 73 | os.Exit(0) 74 | } 75 | } else { 76 | for j := 10; j < 100; j++ { 77 | for _, shape := range shapes { 78 | nums := sets[shape][j] 79 | newShapes := filter(shape, shapes) 80 | for _, num := range nums { 81 | newDigits := append(digits, num) 82 | newOrder := append(order, shape) 83 | if len(digits) == 0 { 84 | backtrack(newShapes, newDigits, newOrder, sets) 85 | continue 86 | } 87 | if has(digits, num) { 88 | continue 89 | } 90 | first, _ := firstAndLastTwo(num) 91 | _, lastD := firstAndLastTwo(digits[len(digits)-1]) 92 | if lastD == first { 93 | backtrack(newShapes, newDigits, newOrder, sets) 94 | } 95 | } 96 | } 97 | } 98 | } 99 | } 100 | 101 | func main() { 102 | sets := map[string][][]int{} 103 | shapes := []string{"t", "s", "p", "hx", "hp", "o"} 104 | 105 | for _, set := range shapes { 106 | sets[set] = make([][]int, 100) 107 | } 108 | for k := 1000; k < 10000; k++ { 109 | firstTwo, lastTwo := firstAndLastTwo(k) 110 | i := float64(k) 111 | if firstTwo < 10 && lastTwo < 10 { 112 | continue 113 | } 114 | 115 | ft, st := getQuadraticRoots(0.5, 0.5, -i) 116 | if isValidRoot(ft, st) { 117 | sets["t"][firstTwo] = append(sets["t"][firstTwo], k) 118 | } 119 | 120 | fs, ss := getQuadraticRoots(1, 0, -i) 121 | if isValidRoot(fs, ss) { 122 | sets["s"][firstTwo] = append(sets["s"][firstTwo], k) 123 | } 124 | 125 | fp, sp := getQuadraticRoots(1.5, -0.5, -i) 126 | if isValidRoot(fp, sp) { 127 | sets["p"][firstTwo] = append(sets["p"][firstTwo], k) 128 | } 129 | 130 | fh, sh := getQuadraticRoots(2, -1, -i) 131 | if isValidRoot(fh, sh) { 132 | sets["hx"][firstTwo] = append(sets["hx"][firstTwo], k) 133 | } 134 | 135 | fhp, shp := getQuadraticRoots(2.5, -1.5, -i) 136 | if isValidRoot(fhp, shp) { 137 | sets["hp"][firstTwo] = append(sets["hp"][firstTwo], k) 138 | } 139 | 140 | fo, so := getQuadraticRoots(3, -2, -i) 141 | if isValidRoot(fo, so) { 142 | sets["o"][firstTwo] = append(sets["o"][firstTwo], k) 143 | } 144 | } 145 | 146 | backtrack(shapes, []int{}, []string{}, sets) 147 | } 148 | -------------------------------------------------------------------------------- /Problem_62_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | "math" 7 | "math/big" 8 | "sort" 9 | "strings" 10 | ) 11 | 12 | type values struct { 13 | count int 14 | number *big.Int 15 | } 16 | 17 | func main() { 18 | numPermutations := flag.Int("number", 5, "Number of permutations to find") 19 | flag.Parse() 20 | 21 | sets := map[string]*values{} 22 | for i := 1; i < math.MaxInt64; i++ { 23 | digitInt64 := int64(i) 24 | digit := big.NewInt(digitInt64) 25 | cube := big.NewInt(1) 26 | cube.Mul(cube, digit).Mul(cube, digit).Mul(cube, digit) 27 | 28 | cubeString := strings.Split(cube.String(), "") 29 | sort.Strings(cubeString) 30 | cubeStringSorted := strings.Join(cubeString, "") 31 | if _, ok := sets[cubeStringSorted]; !ok { 32 | sets[cubeStringSorted] = &values{number: cube, count: 0} 33 | } 34 | sets[cubeStringSorted].count += 1 35 | if sets[cubeStringSorted].count == *numPermutations { 36 | fmt.Println(sets[cubeStringSorted].number) 37 | return 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /Problem_63_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "math" 6 | "math/big" 7 | ) 8 | 9 | func main() { 10 | result := 0 11 | for i := 1; i < 10; i++ { 12 | count := 0 13 | number := big.NewInt(int64(i)) 14 | for n := 1; n <= math.MaxInt64; n++ { 15 | if len(number.String()) != n { 16 | fmt.Println(i, n-1) 17 | break 18 | } 19 | number.Mul(number, big.NewInt(int64(i))) 20 | count += 1 21 | } 22 | result += count 23 | } 24 | 25 | fmt.Println("-----------") 26 | fmt.Println(result) 27 | } 28 | -------------------------------------------------------------------------------- /Problem_64_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | "math" 7 | ) 8 | 9 | // https://projecteuler.net/problem=64 10 | 11 | func gcd(a, b int) int { 12 | a = int(math.Abs(float64(a))) 13 | b = int(math.Abs(float64(b))) 14 | if b == 0 { 15 | return a 16 | } 17 | 18 | return gcd(b, a%b) 19 | } 20 | 21 | func getDenominator(number, lastRoot int) int { 22 | return number - int(math.Pow(float64(lastRoot), 2)) 23 | } 24 | 25 | func getNumerator(denominator, numerator int) int { 26 | return denominator * numerator 27 | } 28 | 29 | type values struct { 30 | numerator int 31 | denominator int 32 | roots []int 33 | } 34 | 35 | func backtrack(n, d, number int) []int { 36 | var stack []values 37 | stack = append(stack, values{n, d, []int{n}}) 38 | for len(stack) > 0 { 39 | stackValue := stack[0] 40 | stack = stack[1:] 41 | 42 | roots := stackValue.roots 43 | numerator := stackValue.numerator 44 | denominator := stackValue.denominator 45 | 46 | newDenominator := getDenominator(number, numerator) 47 | newNumerator := getNumerator(denominator, numerator) 48 | 49 | divisor := gcd(denominator, newDenominator) 50 | newNumerator /= divisor 51 | newDenominator /= divisor 52 | if newNumerator <= 0 || newDenominator <= 0 { 53 | continue 54 | } 55 | if len(roots) > 1 && numerator == n && denominator == d { 56 | return roots 57 | } 58 | 59 | for j := 1; j <= (n+1)*2; j++ { 60 | adjustedNumerator := (j * newDenominator) - newNumerator 61 | if adjustedNumerator <= 0 { 62 | continue 63 | } 64 | stack = append(stack, values{adjustedNumerator, newDenominator, append([]int{j}, roots...)}) 65 | } 66 | } 67 | 68 | return []int{n} 69 | } 70 | 71 | // Obtained from https://en.wikipedia.org/wiki/Periodic_continued_fraction#Canonical_form_and_repetend 72 | func getCount(n int) int { 73 | m := 0 74 | d := 1 75 | a0 := int(math.Sqrt(float64(n))) 76 | a := a0 77 | count := 1 78 | for { 79 | m = d*a - m 80 | denominator := getDenominator(n, m) 81 | if denominator == 0 { 82 | return 0 83 | } 84 | d = denominator / d 85 | a = (a0 + m) / d 86 | //fmt.Println(d, m, a) 87 | if a == 2*a0 { 88 | //fmt.Println(n, count) 89 | break 90 | } 91 | count += 1 92 | } 93 | 94 | return count 95 | } 96 | 97 | func main() { 98 | window := flag.Int("window", 10_000, "Range to find the longest lychrel number") 99 | flag.Parse() 100 | 101 | count := 0 102 | for i := 2; i <= *window; i++ { 103 | //numSqrt := math.Sqrt(float64(i)) 104 | //baseRoot := int(numSqrt) 105 | //numerator, denominator := baseRoot, 1 106 | //resp := backtrack(numerator, denominator, i) 107 | //count += (len(resp) + 1) % 2 108 | count += getCount(i) % 2 109 | //fmt.Println(i, count) 110 | //return 111 | } 112 | fmt.Println(count) 113 | } 114 | -------------------------------------------------------------------------------- /Problem_65_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | "math" 7 | "math/big" 8 | ) 9 | 10 | func main() { 11 | window := flag.Int("window", 10, "The window size") 12 | flag.Parse() 13 | 14 | zero := big.NewInt(0) 15 | ten := big.NewInt(10) 16 | n, m := []*big.Int{big.NewInt(1), big.NewInt(1)}, []*big.Int{big.NewInt(0), big.NewInt(1)} 17 | for i := 1; i < math.MaxInt64; i++ { 18 | index := i - 1 19 | multiplier := big.NewInt(1) 20 | fmt.Println(index, n[0], m[0]) 21 | 22 | if index%3 == 0 { 23 | multiplier.Mul(multiplier, big.NewInt(2)).Mul(multiplier, big.NewInt(int64(index))).Div(multiplier, big.NewInt(3)) 24 | } 25 | 26 | a0, a1 := n[0], n[1] 27 | newN := big.NewInt(1) 28 | n = []*big.Int{a1, newN.Mul(a1, multiplier).Add(a0, newN)} 29 | 30 | b0, b1 := m[0], m[1] 31 | newM := big.NewInt(1) 32 | m = []*big.Int{b1, newM.Mul(b1, multiplier).Add(b0, newM)} 33 | 34 | if index == *window+1 { 35 | break 36 | } 37 | } 38 | 39 | var result int64 40 | start := n[0] 41 | for start.Cmp(zero) > 0 { 42 | result += big.NewInt(1).Mod(start, ten).Int64() 43 | start.Div(start, ten) 44 | } 45 | fmt.Println(result) 46 | } 47 | -------------------------------------------------------------------------------- /Problem_66_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | "math" 7 | "math/big" 8 | "time" 9 | ) 10 | 11 | func getK(a, b, D *big.Float) *big.Float { 12 | aSquared := new(big.Float).Mul(a, a) 13 | bSquared := new(big.Float).Mul(b, b) 14 | 15 | return new(big.Float).Sub(aSquared, new(big.Float).Mul(D, bSquared)) 16 | } 17 | 18 | func composeTriples(a, b, D, k, m *big.Float) (*big.Float, *big.Float, *big.Float) { 19 | absK := new(big.Float).Abs(k) 20 | 21 | am := new(big.Float).Mul(a, m) 22 | db := new(big.Float).Mul(D, b) 23 | amdb := new(big.Float).Add(am, db) 24 | 25 | bm := new(big.Float).Mul(b, m) 26 | abm := new(big.Float).Add(a, bm) 27 | 28 | m2 := new(big.Float).Mul(m, m) 29 | m2D := new(big.Float).Sub(m2, D) 30 | 31 | return new(big.Float).Quo(amdb, absK), new(big.Float).Quo(abm, absK), new(big.Float).Quo(m2D, k) 32 | } 33 | 34 | // BrahmaguptaConsumption 35 | // Apply https://en.wikipedia.org/wiki/Chakravala_method#Brahmagupta's_composition_method to derive solutions for known versions of k 36 | type BrahmaguptaConsumption func(a, b, k *big.Float) (*big.Float, *big.Float) 37 | 38 | func k1(a, b, k *big.Float) (*big.Float, *big.Float) { 39 | a2 := new(big.Float).Mul(a, a) 40 | doubleA2 := new(big.Float).Mul(big.NewFloat(2), a2) 41 | 42 | x := new(big.Float).Add(doubleA2, big.NewFloat(float64(-1*k.Sign()))) 43 | 44 | ab := new(big.Float).Mul(a, b) 45 | y := new(big.Float).Mul(ab, big.NewFloat(2)) 46 | return x, y 47 | } 48 | 49 | func k2(a, b, k *big.Float) (*big.Float, *big.Float) { 50 | a2 := new(big.Float).Mul(a, a) 51 | x := a2.Add(a2, big.NewFloat(float64(-1*k.Sign()))) 52 | 53 | y := new(big.Float).Mul(a, b) 54 | return x, y 55 | } 56 | 57 | func k4(a, b, k *big.Float) (*big.Float, *big.Float) { 58 | one := big.NewFloat(1) 59 | two := big.NewFloat(2) 60 | three := big.NewFloat(3) 61 | if k.Sign() > 0 { 62 | if new(big.Float).Quo(k, b).IsInt() { 63 | a2 := new(big.Float).Mul(a, a) 64 | a2m2 := new(big.Float).Sub(a2, two) 65 | 66 | x := new(big.Float).Quo(a2m2, two) 67 | 68 | ab := new(big.Float).Mul(a, b) 69 | y := new(big.Float).Quo(ab, two) 70 | 71 | return x, y 72 | } else { 73 | a2 := new(big.Float).Mul(a, a) 74 | a2m3 := new(big.Float).Sub(a2, three) 75 | 76 | ad2 := new(big.Float).Quo(a, two) 77 | x := new(big.Float).Mul(ad2, a2m3) 78 | 79 | a2m1 := new(big.Float).Sub(a2, one) 80 | bd2 := new(big.Float).Quo(b, two) 81 | y := new(big.Float).Mul(bd2, a2m1) 82 | 83 | return x, y 84 | } 85 | } 86 | 87 | a2 := new(big.Float).Mul(a, a) 88 | a2p1 := new(big.Float).Add(a2, one) 89 | a2p2 := new(big.Float).Add(a2, two) 90 | a2p3 := new(big.Float).Add(a2, three) 91 | 92 | a2p1ma2p3 := new(big.Float).Mul(a2p1, a2p3) 93 | a2p1ma2p3m2 := new(big.Float).Sub(a2p1ma2p3, two) 94 | a2p1ma2p3m2ma2p2 := new(big.Float).Mul(a2p1ma2p3m2, a2p2) 95 | x := new(big.Float).Quo(a2p1ma2p3m2ma2p2, two) 96 | 97 | ab := new(big.Float).Mul(a, b) 98 | a2p1ma2p3mab := new(big.Float).Mul(a2p1ma2p3, ab) 99 | y := new(big.Float).Quo(a2p1ma2p3mab, two) 100 | 101 | //Note, k=-4 is useful to find a solution to Pell's Equation, but it is not always the smallest integer pair. 102 | //panic("Do not apply when k=-4") 103 | return x, y 104 | } 105 | 106 | func findMinimalM(a, b, D, k *big.Float) *big.Float { 107 | inflectionPoint := big.NewFloat(math.MaxInt64) 108 | lastM := new(big.Float) 109 | lastK := big.NewFloat(math.MaxInt64) 110 | m := big.NewFloat(1) 111 | incrementer := big.NewFloat(1) 112 | 113 | value, _ := k.Float64() 114 | if value < 1 { 115 | value = 1 * float64(k.Sign()) 116 | } 117 | kShift := big.NewFloat(float64(int(value) * k.Sign())) 118 | for { 119 | if m.Cmp(big.NewFloat(1000)) == 1 { 120 | return lastM 121 | } 122 | 123 | bigM := new(big.Float).Copy(m) 124 | _, newB, newK := composeTriples(a, b, D, k, bigM) 125 | 126 | absNewK := new(big.Float).Abs(newK) 127 | absNewK.Mul(absNewK, k) 128 | absNewK = new(big.Float).Abs(absNewK) 129 | 130 | if newB.IsInt() && absNewK.IsInt() { 131 | if absNewK.Cmp(inflectionPoint) == 1 && newB.Cmp(new(big.Float)) == 1 { 132 | return lastM 133 | } 134 | 135 | inflectionPoint = absNewK 136 | if lastK.Cmp(absNewK) == 1 { 137 | lastK = absNewK 138 | lastM = bigM 139 | } 140 | 141 | incrementer = kShift 142 | } 143 | 144 | m.Add(m, incrementer) 145 | } 146 | } 147 | 148 | func isExemptK(k *big.Float) bool { 149 | kAbs := new(big.Float).Abs(k) 150 | return kAbs.Cmp(big.NewFloat(1)) == 0 || kAbs.Cmp(big.NewFloat(2)) == 0 || k.Cmp(big.NewFloat(4)) == 0 151 | } 152 | 153 | func PellsEquation(window float64) { 154 | 155 | solutions := map[float64]BrahmaguptaConsumption{ 156 | 1: k1, 157 | 2: k2, 158 | 4: k4, 159 | } 160 | maxIterations := 200 161 | skipped := 0 162 | 163 | // Pell's Equation 164 | // https://en.wikipedia.org/wiki/Pell%27s_equation#Solutions 165 | // x^2 - D * y^2 = 1 166 | // a^2 - D * b^2 = k 167 | 168 | // Uses the Chakravala method: http://en.wikipedia.org/wiki/Chakravala_method 169 | maxD, x, y := big.NewFloat(0), big.NewFloat(math.MinInt64), big.NewFloat(0) 170 | for i := 2.0; i <= window; i++ { 171 | D := big.NewFloat(i) 172 | sqrtD := new(big.Float).Sqrt(D) 173 | if sqrtD.IsInt() { 174 | continue 175 | } 176 | 177 | floatSqrtD := new(big.Float).Copy(sqrtD).SetPrec(1) 178 | b := big.NewFloat(1) 179 | a, k := floatSqrtD, getK(floatSqrtD, b, D) 180 | kp1 := new(big.Float).Add(floatSqrtD, big.NewFloat(1)) 181 | newK := getK(kp1, b, D) 182 | isSqrt := true 183 | 184 | if new(big.Float).Abs(newK).Cmp(new(big.Float).Abs(k)) == -1 { 185 | a, k = kp1, newK 186 | } 187 | 188 | fmt.Println("--------------------") 189 | fmt.Printf("Starting %f, %f, %f, %f\n", D, a, b, k) 190 | originalA, originalB, originalK := new(big.Float).Copy(a), new(big.Float).Copy(b), new(big.Float).Copy(k) 191 | 192 | iterations := 0 193 | disableSqrt := false 194 | for { 195 | if !isSqrt && isExemptK(k) { 196 | break 197 | } 198 | 199 | m := findMinimalM(a, b, D, k) 200 | if m.Cmp(new(big.Float)) < 0 { 201 | panic("m cannot be less than 0") 202 | } 203 | fmt.Printf("Before %f, %f, %f, %f\n", a, b, k, m) 204 | 205 | a, b, k = composeTriples(a, b, D, k, m) 206 | isSqrt = false 207 | 208 | kAbs := new(big.Float).Abs(k) 209 | kSqrt := new(big.Float).Sqrt(kAbs) 210 | if kSqrt.IsInt() && !isExemptK(k) && !disableSqrt { 211 | fmt.Println("kSquared Before", a, b, k) 212 | isSqrt = true 213 | a.Quo(a, kSqrt) 214 | 215 | b.Quo(b, kSqrt) 216 | k.Quo(k, kAbs) 217 | } 218 | 219 | if iterations%maxIterations == 0 { 220 | if disableSqrt { 221 | break 222 | } 223 | 224 | fmt.Println("Disabling sqrt") 225 | a = new(big.Float).Copy(originalA) 226 | b = new(big.Float).Copy(originalB) 227 | k = new(big.Float).Copy(originalK) 228 | disableSqrt = true 229 | } 230 | 231 | fmt.Printf("After %f, %f, %f\n", a, b, k) 232 | iterations++ 233 | } 234 | 235 | index, _ := new(big.Float).Abs(k).Float64() 236 | if !k.IsInt() || index > 4 { 237 | skipped += 1 238 | continue 239 | } 240 | newA, newB := solutions[index](a, b, k) 241 | 242 | fmt.Printf("*****Solved in %d iterations**********\n", iterations) 243 | fmt.Println(k) 244 | fmt.Printf("Base solution %f, %f, %f\n", D, a, b) 245 | if k.Cmp(big.NewFloat(1)) == 0 { 246 | if a.Cmp(x) == 1 { 247 | x = a 248 | y = b 249 | maxD = D 250 | } 251 | } else { 252 | fmt.Printf("%f, %f, %f\n", D, newA, newB) 253 | 254 | if newA.Cmp(x) == 1 { 255 | x = newA 256 | y = newB 257 | maxD = D 258 | } 259 | } 260 | } 261 | 262 | fmt.Println("------------") 263 | fmt.Printf("Skippped %d operations\n", skipped) 264 | fmt.Printf("%f, %f, %f\n", maxD, x, y) 265 | } 266 | 267 | func getDenominator(number, lastRoot int) int { 268 | return number - int(math.Pow(float64(lastRoot), 2)) 269 | } 270 | 271 | func solvePell(D float64) (float64, float64, int) { 272 | t := math.Sqrt(D) 273 | a := math.Floor(t) 274 | iterations := 0 275 | if a == t { 276 | return 0, 0, iterations 277 | } 278 | b, c, r := a, 1.0, float64(int64(a)<<1) 279 | e1, e2 := 1.0, 0.0 280 | f1, f2 := 0.0, 1.0 281 | for { 282 | b = (r * c) - b 283 | c = math.Floor((D - (b * b)) / c) 284 | r = math.Floor((a + b) / c) 285 | e1, e2 = e2, e1+e2*r 286 | f1, f2 = f2, f1+f2*r 287 | x, y := f2*a+e2, f2 288 | fmt.Printf("--%f %f\n", x, y) 289 | time.Sleep(500 * time.Millisecond) 290 | //sqrtD := big.NewFloat(t) 291 | 292 | // Go has some precision issue that makes this round off to 0 instead of 1 293 | // for a number of solutions. 294 | // It is highly impractical but in the future, just use the PellersEquation() method 295 | // as that works fine 296 | x2 := x + (t * y) 297 | Dy2 := x - (t * y) 298 | fmt.Printf("%f %f %f %f\n", x, y, x2, Dy2) 299 | 300 | if x2*Dy2 == 1 { 301 | return x, y, iterations 302 | } 303 | iterations += 1 304 | } 305 | } 306 | 307 | func getNumerator(D float64) (*big.Float, *big.Float, int) { 308 | x := math.Floor(math.Sqrt(D)) 309 | y, z, r := x, 1.0, float64(int(x)<<1) 310 | x1, x2 := big.NewFloat(1), new(big.Float) 311 | y1, y2 := new(big.Float), big.NewFloat(1) 312 | iterations := 0 313 | for { 314 | y = r*z - y 315 | z = math.Floor((D - math.Pow(y, 2)) / z) 316 | r = math.Floor((x + y) / z) 317 | 318 | x1, x2 = x2, new(big.Float).Copy(x1).Add(x1, new(big.Float).Mul(x2, big.NewFloat(r))) 319 | y1, y2 = y2, new(big.Float).Copy(x1).Add(y1, new(big.Float).Mul(y2, big.NewFloat(r))) 320 | 321 | a, b := new(big.Float).Add(x2, new(big.Float).Mul(y2, big.NewFloat(x))), y2 322 | //if a.IsInf() || b.IsInf() || iterations > 200 { 323 | // return new(big.Float), new(big.Float), iterations 324 | //} 325 | a2 := new(big.Float).Mul(a, a) 326 | b2 := new(big.Float).Mul(b, b) 327 | remainder := new(big.Float).Sub(a2, new(big.Float).Mul(big.NewFloat(D), b2)) 328 | fmt.Println(remainder) 329 | time.Sleep(500 * time.Millisecond) 330 | if remainder.Cmp(big.NewFloat(1)) == 0 { 331 | return a, b, iterations 332 | } 333 | 334 | iterations += 1 335 | } 336 | } 337 | 338 | func main() { 339 | window := flag.Float64("window", 10, "window size") 340 | flag.Parse() 341 | 342 | PellsEquation(*window) 343 | 344 | //maxX := float64(math.MinInt64) 345 | //y := 0.0 346 | //D := 0.0 347 | //skipped := 0 348 | // 349 | //for i := 61.0; i <= *window; i++ { 350 | // Dsqrt := math.Sqrt(i) 351 | // if math.Floor(Dsqrt)-Dsqrt == 0 { 352 | // continue 353 | // } 354 | // num, denum, iterations := solvePell(i) 355 | // fmt.Println(i, num, denum, iterations) 356 | // if iterations > 200 { 357 | // skipped += 1 358 | // } 359 | // if num > maxX { 360 | // maxX = num 361 | // D = i 362 | // y = denum 363 | // } 364 | //} 365 | ////time.Sleep(500 * time.Millisecond) 366 | // 367 | //fmt.Println(D, maxX, y, skipped) 368 | } 369 | -------------------------------------------------------------------------------- /Problem_66_Euler/main.py: -------------------------------------------------------------------------------- 1 | def solvePell(D): 2 | t = D ** 0.5 # square root 3 | if (a := int(t)) == t: return 0 # D is square, no solution 4 | b, c, r = a, 1, a << 1 5 | e1, e2 = 1, 0 6 | f1, f2 = 0, 1 7 | while True: 8 | b = r * c - b 9 | c = (D - b * b) // c 10 | r = (a + b) // c 11 | print(b,c,r) 12 | e1, e2 = e2, e1 + e2 * r 13 | f1, f2 = f2, f1 + f2 * r 14 | x, y = f2 * a + e2, f2 15 | print(x, y, x * x - D * y * y) 16 | if x * x - D * y * y == 1: return x 17 | 18 | print(max(range(61, 62), key=solvePell)) # 661 -------------------------------------------------------------------------------- /Problem_67_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | // https://projecteuler.net/problem=67 4 | 5 | import ( 6 | "bufio" 7 | "flag" 8 | "fmt" 9 | "os" 10 | "strconv" 11 | "strings" 12 | ) 13 | 14 | func DFS(arr [][]int) int { 15 | for i := len(arr[len(arr)-1]) - 2; i >= 0; i-- { 16 | for j := 0; j <= i; j++ { 17 | fmt.Println(i, j) 18 | if arr[i+1][j] > arr[i+1][j+1] { 19 | arr[i][j] += arr[i+1][j] 20 | } else { 21 | arr[i][j] += arr[i+1][j+1] 22 | } 23 | } 24 | } 25 | 26 | return arr[0][0] 27 | } 28 | 29 | func main() { 30 | fileName := flag.String("file", "input.txt", "File to read integers from") 31 | flag.Parse() 32 | 33 | input, err := os.Open(*fileName) 34 | if err != nil { 35 | panic(err) 36 | } 37 | defer input.Close() 38 | 39 | buffer := bufio.NewScanner(input) 40 | var stringArr []string 41 | var triangleArr [][]int 42 | for buffer.Scan() { 43 | var numArr []int 44 | stringArr = strings.Split(strings.Trim(buffer.Text(), " "), " ") 45 | for _, el := range stringArr { 46 | val, _ := strconv.Atoi(el) 47 | numArr = append(numArr, val) 48 | } 49 | triangleArr = append(triangleArr, numArr) 50 | } 51 | fmt.Println(triangleArr) 52 | result := DFS(triangleArr) 53 | fmt.Println(result) 54 | } 55 | -------------------------------------------------------------------------------- /Problem_68_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | "math" 7 | "sort" 8 | ) 9 | 10 | // https://projecteuler.net/problem=68 11 | 12 | // https://en.wikipedia.org/wiki/Heap%27s_algorithm 13 | func getPermutations(arr []int) [][]int { 14 | var helper func([]int, int) 15 | res := [][]int{} 16 | 17 | helper = func(arr []int, n int) { 18 | if n == 1 { 19 | tmp := make([]int, len(arr)) 20 | copy(tmp, arr) 21 | res = append(res, tmp) 22 | } else { 23 | for i := 0; i < n; i++ { 24 | helper(arr, n-1) 25 | if n%2 == 1 { 26 | tmp := arr[i] 27 | arr[i] = arr[n-1] 28 | arr[n-1] = tmp 29 | } else { 30 | tmp := arr[0] 31 | arr[0] = arr[n-1] 32 | arr[n-1] = tmp 33 | } 34 | } 35 | } 36 | } 37 | helper(arr, len(arr)) 38 | return res 39 | } 40 | 41 | func getCombinations(arr, rest []int, n int, result [][]int) [][]int { 42 | if n == 0 { 43 | return [][]int{arr} 44 | } else { 45 | for i, k := range rest { 46 | result = append(result, getCombinations(append([]int{k}, arr...), rest[i+1:], n-1, [][]int{})...) 47 | } 48 | } 49 | 50 | return result 51 | } 52 | 53 | type entry struct { 54 | expectedSum int 55 | digits [][]int 56 | usedDigits map[int]struct{} 57 | result [][]int 58 | finalValue int 59 | } 60 | 61 | func filter(arr [][]int, filterMap map[int]struct{}, expectedSum int) [][]int { 62 | var newArr [][]int 63 | for i := 0; i < len(arr); i++ { 64 | _, ok1 := filterMap[arr[i][0]] 65 | _, ok2 := filterMap[arr[i][1]] 66 | if !ok1 && !ok2 && sum(arr[i]) == expectedSum { 67 | newArr = append(newArr, arr[i]) 68 | } 69 | } 70 | 71 | return newArr 72 | } 73 | 74 | func sum(a []int) int { 75 | result := 0 76 | for i := 0; i < len(a); i++ { 77 | result += a[i] 78 | } 79 | return result 80 | } 81 | 82 | func backtrack(n int, digitMap map[int][][]int) []entry { 83 | var queue []entry 84 | firstEntry := entry{ 85 | digits: digitMap[n], 86 | usedDigits: make(map[int]struct{}), 87 | result: make([][]int, 0), 88 | expectedSum: 0, 89 | } 90 | queue = append(queue, firstEntry) 91 | 92 | var result []entry 93 | for len(queue) > 0 { 94 | cur := queue[0] 95 | queue = queue[1:] 96 | 97 | if len(cur.usedDigits) == len(digitMap) { 98 | if len(cur.digits) > 0 { 99 | panic(cur.digits) 100 | } 101 | resultLength := len(digitMap) / 2 102 | if cur.result[resultLength-1][1] == cur.result[resultLength-2][2] && cur.result[0][1] == cur.result[resultLength-1][2] { 103 | var nums []int 104 | for _, num := range cur.result { 105 | nums = append(nums, num...) 106 | } 107 | cur.finalValue = getValue(nums) 108 | result = append(result, cur) 109 | } 110 | } 111 | 112 | for _, d := range cur.digits { 113 | if len(cur.result) > 0 && getValue(cur.result[0]) > getValue(d) { 114 | continue 115 | } 116 | 117 | newUsedDigits := map[int]struct{}{} 118 | for k, v := range cur.usedDigits { 119 | newUsedDigits[k] = v 120 | } 121 | newUsedDigits[d[0]] = struct{}{} 122 | newUsedDigits[d[1]] = struct{}{} 123 | 124 | newResult := make([][]int, len(cur.result)) 125 | copy(newResult, cur.result) 126 | newResult = append(newResult, d) 127 | 128 | newSum := sum(d) 129 | newDigits := filter(digitMap[d[2]], newUsedDigits, newSum) 130 | newEntry := entry{ 131 | digits: newDigits, 132 | usedDigits: newUsedDigits, 133 | result: newResult, 134 | expectedSum: newSum, 135 | } 136 | 137 | queue = append(queue, newEntry) 138 | } 139 | } 140 | 141 | return result 142 | } 143 | 144 | func getValue(digits []int) int { 145 | value := 0 146 | power := 0 147 | for i := 0; i < len(digits); i++ { 148 | number := float64(digits[len(digits)-i-1]) 149 | value += int(math.Pow(10, float64(power)) * number) 150 | power += int(math.Floor(math.Log10(number)) + 1) 151 | } 152 | 153 | return value 154 | } 155 | 156 | func main() { 157 | nGonSize := flag.Int("d", 5, "N-gon ring to generate") 158 | expectedDigits := flag.Int("num", 16, "Expected number of digits to find") 159 | flag.Parse() 160 | 161 | nGonDigits := 2 * *nGonSize 162 | 163 | digits := []int{} 164 | for i := 1; i <= nGonDigits; i++ { 165 | digits = append(digits, i) 166 | } 167 | 168 | middleDigitMap := map[int][][]int{} 169 | for _, k := range getCombinations([]int{}, digits, 3, [][]int{}) { 170 | for _, d := range getPermutations(k) { 171 | middleDigitMap[d[1]] = append(middleDigitMap[d[1]], d) 172 | } 173 | } 174 | 175 | var result []entry 176 | for i := 1; i <= nGonDigits; i++ { 177 | result = append(result, backtrack(i, middleDigitMap)...) 178 | } 179 | 180 | sort.Slice(result, func(i, j int) bool { 181 | if result[i].expectedSum == result[j].expectedSum { 182 | return result[i].finalValue < result[j].finalValue 183 | } 184 | 185 | return result[i].expectedSum < result[j].expectedSum 186 | }) 187 | 188 | maxNum := math.MinInt64 189 | for _, d := range result { 190 | numDigits := int(math.Log10(float64(d.finalValue))) + 1 191 | if d.finalValue > maxNum && numDigits == *expectedDigits { 192 | maxNum = d.finalValue 193 | } 194 | fmt.Println(d.expectedSum, d.result, d.finalValue, int(math.Log10(float64(d.finalValue)))+1) 195 | } 196 | fmt.Println("-------------") 197 | fmt.Println(maxNum) 198 | } 199 | -------------------------------------------------------------------------------- /Problem_69_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | "math" 7 | ) 8 | 9 | // https://projecteuler.net/problem=69 10 | 11 | func isPrime(n int) bool { 12 | i := 2 13 | if n == 0 || n == 1 { 14 | return false 15 | } 16 | for i <= int(math.Sqrt(float64(n))) { 17 | if n%i == 0 { 18 | return false 19 | } 20 | i++ 21 | } 22 | 23 | return true 24 | } 25 | 26 | func main() { 27 | window := flag.Int("window", 1_000_000, "The window size") 28 | flag.Parse() 29 | 30 | fmt.Println(eulerProductFormula(*window)) 31 | return 32 | 33 | // https://projecteuler.net/overview=0069 34 | // This is so cracked, basically the max(n/totient(n)) is the max prime product to the number n 35 | n := 1 36 | for i := 2; n*i < *window; i++ { 37 | if isPrime(i) { 38 | fmt.Println(n) 39 | n *= i 40 | } 41 | } 42 | 43 | fmt.Println("------------------") 44 | fmt.Println(n) 45 | } 46 | 47 | func eulerProductFormula(window int) int { 48 | maxN, n := 0.0, 2 49 | var primes []int 50 | for i := 2; i <= window; i++ { 51 | count := float64(i) 52 | if isPrime(i) { 53 | primes = append(primes, i) 54 | count -= 1 55 | } else { 56 | // https://en.wikipedia.org/wiki/Euler%27s_totient_function#Computing_Euler's_totient_function 57 | for _, p := range primes { 58 | if i%p == 0 { 59 | count *= 1 - (1 / float64(p)) 60 | } 61 | } 62 | } 63 | 64 | phiN := float64(i) / count 65 | if phiN > maxN { 66 | //fmt.Println(phiN) 67 | maxN = phiN 68 | n = i 69 | } 70 | } 71 | 72 | return n 73 | } 74 | -------------------------------------------------------------------------------- /Problem_6_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | 4 | import ( 5 | "flag" 6 | "fmt" 7 | ) 8 | 9 | 10 | // https://projecteuler.net/problem=6 11 | 12 | func getLinearAPSum(n int) int{ 13 | return (n * (n + 1)) * (n * (n + 1)) / 4 14 | } 15 | 16 | func getSquareAPSum(n int) int{ 17 | return ( n * (n + 1) * ((2 *n) + 1) ) / 6 18 | } 19 | 20 | func main() { 21 | maxNumPtr := flag.Int("number", 100, "Integer for the max range") 22 | flag.Parse() 23 | fmt.Println(-getSquareAPSum(*maxNumPtr) + getLinearAPSum(*maxNumPtr)) 24 | } 25 | -------------------------------------------------------------------------------- /Problem_70_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | "math" 7 | "sort" 8 | "strconv" 9 | "strings" 10 | ) 11 | 12 | // https://projecteuler.net/problem=70 13 | 14 | func isPrime(n int) bool { 15 | i := 2 16 | if n == 0 || n == 1 { 17 | return false 18 | } 19 | for i <= int(math.Sqrt(float64(n))) { 20 | if n%i == 0 { 21 | return false 22 | } 23 | i++ 24 | } 25 | 26 | return true 27 | } 28 | 29 | func bruteforce(window int) int { 30 | n := 1 31 | minN := float64(math.MaxInt64) 32 | var primes []int 33 | 34 | for i := 2; i <= window; i++ { 35 | count := float64(i) 36 | if isPrime(i) { 37 | primes = append(primes, i) 38 | count -= 1 39 | continue 40 | } else { 41 | // https://en.wikipedia.org/wiki/Euler%27s_totient_function#Computing_Euler's_totient_function 42 | for _, p := range primes { 43 | if i%p == 0 { 44 | count *= 1 - (1 / float64(p)) 45 | } 46 | } 47 | } 48 | 49 | a := strings.Split(strconv.Itoa(int(count)), "") 50 | b := strings.Split(strconv.Itoa(i), "") 51 | sort.Strings(a) 52 | sort.Strings(b) 53 | 54 | if strings.Join(a, "") == strings.Join(b, "") { 55 | fmt.Println(i, int(count)) 56 | phiN := float64(i) / count 57 | if phiN < minN { 58 | minN = phiN 59 | n = i 60 | } 61 | } 62 | } 63 | 64 | fmt.Println("------------------") 65 | fmt.Println(n) 66 | 67 | return n 68 | } 69 | 70 | func main() { 71 | window := flag.Int("window", 10_000_000, "The window size") 72 | flag.Parse() 73 | 74 | // https://mathworld.wolfram.com/TotientFunction.html 75 | // The idea for the new solution is that a permutation close to n will happen when the prime is close to the count 76 | // We already know it will be close to prime as the phi(n) = n - 1 77 | // To avoid searching for those values, we assume that n is a product of two primes 78 | // therefore if n = p*q, then phi(n) = phi(pq) = (p-1)(q-1) 79 | // The entire body of this solution is to find the two primes that fit within n < N 80 | // and then use the value to get the solution that minimises the n/phi(n) 81 | // We cannot use a prime as we already know that n-1 compared to n will not permute but will be minimal for n/phi(n) 82 | 83 | sqrtN := int(math.Sqrt(float64(*window))) 84 | primeRange := int(math.Pow(10, math.Floor(math.Log10(float64(sqrtN))+2))) 85 | var primes []int 86 | minPhi := float64(math.MaxInt64) 87 | maxN := 0 88 | for i := sqrtN - primeRange; i < sqrtN+primeRange; i++ { 89 | if i < 0 { 90 | continue 91 | } 92 | if isPrime(i) { 93 | primes = append(primes, i) 94 | } 95 | } 96 | 97 | for i := 0; i < len(primes); i++ { 98 | for j := i + 1; j < len(primes); j++ { 99 | prod := primes[i] * primes[j] 100 | if prod > *window { 101 | break 102 | } 103 | 104 | phiN := (prod + 1) - (primes[i] + primes[j]) // Expanded version of (p-1)(q-1) 105 | a := strings.Split(strconv.Itoa(prod), "") 106 | b := strings.Split(strconv.Itoa(phiN), "") 107 | sort.Strings(a) 108 | sort.Strings(b) 109 | 110 | if strings.Join(a, "") == strings.Join(b, "") { 111 | ratio := float64(prod) / float64(phiN) 112 | 113 | fmt.Println(prod, phiN, ratio) 114 | if ratio < minPhi { 115 | minPhi = ratio 116 | maxN = prod 117 | } 118 | } 119 | } 120 | } 121 | 122 | fmt.Println("------------------") 123 | fmt.Println(maxN) 124 | } 125 | -------------------------------------------------------------------------------- /Problem_71_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | "math/big" 7 | ) 8 | 9 | // https://projecteuler.net/problem=71 10 | 11 | func main() { 12 | window := flag.Int64("window", 1_000_000, "The window size") 13 | flag.Parse() 14 | 15 | num, denum := int64(3), int64(7) 16 | upperFrac := big.NewRat(3, 7) 17 | lowerFrac := big.NewRat(2, 5) 18 | minRat := big.NewRat(1, 1) 19 | maxRat := big.NewRat(0, 1) 20 | result := big.NewRat(1, 1) 21 | 22 | zero := new(big.Rat) 23 | for { 24 | if denum > *window || num > *window { 25 | break 26 | } 27 | 28 | currRat := big.NewRat(num, denum) 29 | newMinRat := new(big.Rat).Sub(upperFrac, currRat) 30 | newMaxRat := new(big.Rat).Sub(currRat, lowerFrac) 31 | if newMinRat.Cmp(minRat) < 0 && newMaxRat.Cmp(maxRat) > 0 && newMinRat.Cmp(zero) > 0 && newMaxRat.Cmp(zero) > 0 { 32 | minRat = newMinRat 33 | maxRat = newMaxRat 34 | result = currRat 35 | } 36 | 37 | if big.NewRat(num, denum).Cmp(upperFrac) > 0 { 38 | denum += 1 39 | } else if big.NewRat(num, denum).Cmp(lowerFrac) < 0 { 40 | num += 1 41 | } else { 42 | num += 1 43 | denum += 1 44 | } 45 | } 46 | 47 | fmt.Println(result) 48 | } 49 | -------------------------------------------------------------------------------- /Problem_72_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | "math" 7 | ) 8 | 9 | // https://projecteuler.net/problem=72 10 | 11 | func isPrime(n int) bool { 12 | sqrt := int(math.Sqrt(float64(n))) + 1 13 | for i := 2; i < sqrt; i++ { 14 | if n%i == 0 { 15 | return false 16 | } 17 | } 18 | 19 | return true 20 | } 21 | 22 | func eulerTotientMethod(window int) int { 23 | totalFractions := 0.0 24 | var primes []int 25 | 26 | for i := 2; i <= window; i++ { 27 | count := float64(i) 28 | if isPrime(i) { 29 | primes = append(primes, i) 30 | count -= 1 31 | } else { 32 | // https://en.wikipedia.org/wiki/Euler%27s_totient_function#Computing_Euler's_totient_function 33 | for _, p := range primes { 34 | if i%p == 0 { 35 | count *= 1 - (1 / float64(p)) 36 | } 37 | } 38 | } 39 | 40 | totalFractions += count 41 | } 42 | 43 | return int(totalFractions) 44 | } 45 | 46 | func main() { 47 | window := flag.Int("window", 1_000_000, "The window size") 48 | flag.Parse() 49 | 50 | data := []int{0, 0} 51 | for i := 2; i < *window+1; i++ { 52 | data = append(data, i-1) 53 | } 54 | 55 | for i := 2; i < len(data); i++ { 56 | for j := i * 2; j < len(data); j += i { 57 | data[j] -= data[i] 58 | } 59 | } 60 | 61 | maxVal := 0 62 | for i, _ := range data { 63 | maxVal += data[i] 64 | } 65 | 66 | fmt.Println(maxVal) 67 | } 68 | -------------------------------------------------------------------------------- /Problem_73_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | "math" 7 | ) 8 | 9 | // https://projecteuler.net/problem=73 10 | 11 | func gcd(a, b int) int { 12 | if b == 0 { 13 | return a 14 | } 15 | 16 | return gcd(b, a%b) 17 | } 18 | 19 | func main() { 20 | window := flag.Int("window", 12_000, "The window size") 21 | flag.Parse() 22 | 23 | totalSum := 0 24 | 25 | // 2/5 26 | // 3/7 3/8 27 | // 4/9 4/10 4/11 28 | // 5/11 5/12 5/13 5/14 29 | // 6/13 6/14 6/15 6/16 6/17 30 | // 7/15 7/16 7/17 7/18 7/19 7/20 31 | 32 | for i := 1; i <= *window/2; i++ { 33 | for j := 2*i + 1; j < 3*i; j += 1 { 34 | if j > *window { 35 | break 36 | } 37 | //fmt.Println(i, j) 38 | if gcd(i, j) == 1 { 39 | totalSum += 1 40 | } 41 | } 42 | } 43 | 44 | fmt.Println(totalSum) 45 | } 46 | 47 | func isPrime(n int) bool { 48 | i := 2 49 | if n == 0 || n == 1 { 50 | return false 51 | } 52 | for i <= int(math.Sqrt(float64(n))) { 53 | if n%i == 0 { 54 | return false 55 | } 56 | i++ 57 | } 58 | 59 | return true 60 | } 61 | 62 | func bruteforce(window *int) { 63 | 64 | totalSum := 0 65 | 66 | var primes []int 67 | numReductions := map[int]int{} 68 | denumReductions := map[int]int{} 69 | 70 | for j := 2; j <= *window; j++ { 71 | if isPrime(j) { 72 | primes = append(primes, j) 73 | } 74 | } 75 | 76 | // 2/5 77 | // 3/7 3/8 78 | // 4/9 4/10 4/11 79 | // 5/11 5/12 5/13 5/14 80 | // 6/13 6/14 6/15 6/16 6/17 81 | // 7/15 82 | 83 | for i := 1; i <= *window/2; i++ { 84 | for j := 2*i + 1; j < 3*i; j += 1 { 85 | if j > *window { 86 | break 87 | } 88 | fmt.Println("+", i, j) 89 | totalSum += 1 90 | for _, prime := range primes { 91 | if prime > i { 92 | break 93 | } 94 | if i%prime == 0 && j%prime == 0 { 95 | numReductions[i] += 1 96 | denumReductions[j] += 1 97 | fmt.Println("-", i, j) 98 | totalSum -= 1 99 | break 100 | } 101 | } 102 | } 103 | } 104 | 105 | //n(1 + 1.25(n-10)) 106 | fmt.Println(numReductions) 107 | fmt.Println(denumReductions) 108 | fmt.Println(totalSum) 109 | } 110 | -------------------------------------------------------------------------------- /Problem_74_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | ) 7 | 8 | // https://projecteuler.net/problem=74 9 | 10 | func breakNumber(n int) []int { 11 | result := []int{} 12 | for n > 0 { 13 | result = append([]int{n % 10}, result...) 14 | n /= 10 15 | } 16 | 17 | return result 18 | } 19 | 20 | func getFactorialSum(n int, factorials map[int]int) int { 21 | total := 0 22 | for _, j := range breakNumber(n) { 23 | total += factorials[j] 24 | } 25 | 26 | return total 27 | } 28 | 29 | func main() { 30 | window := flag.Int("window", 1_000_000, "The window size") 31 | nonRepeatingTerms := flag.Int("terms", 60, "Number of non-repeating terms to find") 32 | flag.Parse() 33 | 34 | run(*window, *nonRepeatingTerms) 35 | } 36 | 37 | func run(window int, nonRepeatingTerms int) { 38 | count := 0 39 | states := map[int]int{} 40 | factorials := map[int]int{0: 1} 41 | for i := 1; i < 10; i++ { 42 | factorials[i] = factorials[i-1] * i 43 | } 44 | 45 | results := map[int]int{} 46 | for i := 2; i < window; i++ { 47 | node := i 48 | sequence := map[int]int{} 49 | 50 | for { 51 | _, ok := sequence[node] 52 | _, ok2 := results[node] 53 | if ok || ok2 { 54 | fmt.Println(i, len(sequence)) 55 | results[i] = len(sequence) + results[node] 56 | if results[i] == nonRepeatingTerms { 57 | count += 1 58 | } 59 | 60 | break 61 | } 62 | 63 | newNode, ok := states[node] 64 | if !ok { 65 | newNode = getFactorialSum(node, factorials) 66 | states[node] = newNode 67 | } 68 | 69 | sequence[node] = newNode 70 | node = newNode 71 | } 72 | } 73 | 74 | fmt.Println(count) 75 | } 76 | -------------------------------------------------------------------------------- /Problem_74_Euler/main_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "testing" 4 | 5 | func BenchmarkMyFunction(b *testing.B) { 6 | run(1_000_000, 60) 7 | } 8 | -------------------------------------------------------------------------------- /Problem_75_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | // https://projecteuler.net/problem=75 4 | 5 | import ( 6 | "flag" 7 | "fmt" 8 | "math" 9 | ) 10 | 11 | func bruteforce(window int) { 12 | perimeters := make([]int, window+1) 13 | for perimeter := 2; perimeter <= window; perimeter += 2 { 14 | if perimeters[perimeter] == 1 { 15 | perimeters[perimeter] = 0 16 | continue 17 | } 18 | for i := 2; i <= window; i++ { 19 | for j := i + 1; j < perimeter-i; j++ { 20 | k := perimeter - i - j 21 | if (i*i)+(j*j) == k*k { 22 | fmt.Println(perimeter, i, j, k) 23 | perimeters[perimeter] += 1 24 | } 25 | } 26 | } 27 | } 28 | 29 | count := 0 30 | for _, v := range perimeters { 31 | if v != 0 { 32 | count += 1 / v 33 | } 34 | } 35 | 36 | fmt.Println(count) 37 | } 38 | 39 | func gcd(a, b int) int { 40 | if b == 0 { 41 | return a 42 | } 43 | 44 | return gcd(b, a%b) 45 | } 46 | 47 | func main() { 48 | window := flag.Int("window", 1_500_000, "Window to search for the perimeter values") 49 | flag.Parse() 50 | 51 | //bruteforce(*window) 52 | fmt.Println("*******************************") 53 | //singleIntegerRightAngle(*window) 54 | eulersMethod(*window) 55 | } 56 | 57 | // This is so much faster than the method I derived for finding pythagorean triples 58 | func eulersMethod(window int) { 59 | perimeters := map[int]int{} 60 | for m := 2; m <= int(math.Sqrt(float64(window/2)))+1; m++ { 61 | for n := 1; n <= m; n++ { 62 | if (m-n)%2 == 1 && gcd(m, n) == 1 { 63 | a := m*m - n*n 64 | b := 2 * m * n 65 | c := m*m + n*n 66 | perimeter := a + b + c 67 | //fmt.Println(perimeter, a, b, c) 68 | for j := perimeter; j <= window; j += perimeter { 69 | perimeters[j] += 1 70 | } 71 | } 72 | } 73 | } 74 | 75 | counts := 0 76 | for _, v := range perimeters { 77 | counts += 1 / v 78 | } 79 | 80 | fmt.Println(counts) 81 | } 82 | 83 | func singleIntegerRightAngle(window int) { 84 | 85 | // From my article: https://blog.bakman.build/blogs/unravelling-mathematical-threesomes.html 86 | // You can obtain a pythagorean triples using just one value "b" and some pythagorean distance "k" 87 | // So perimeter = a + b + c = (b^2 / k) + b 88 | // perimeter = (b^2 / k) + b 89 | // k = b ^ 2 / (perimeter - b) 90 | 91 | // To solve this, k must be an integer based on the equation above 92 | // In getting b, we can conclude that it is always bounded within 93 | // perimeter/2 as no pythagorean value can be greater than its perimeter halved. 94 | // If we consider that the longest side, the hypotenuse "c" is less than the perimeter halved: 95 | // (a + b + c) / 2 > c 96 | // a + b + c > 2c 97 | // a + b > c 98 | // a + b > sqrt(a^2 + b^2) which will hold true as 99 | // (a + b)^ 2 > a^2 + b^2 by 2ab once you expand the factors 100 | 101 | // In deriving the solution for this problem, we can have permutations of the same tuple, this therefore checks 102 | // that the triple found in (a,b,c) has not been seen before. 103 | // We then increment the perimeter and adds the count at the end of the iterations from 0 to the window. 104 | perimeters := map[int]int{} 105 | for perimeter := 2; perimeter <= window; perimeter += 2 { 106 | seen := map[[3]int]bool{} 107 | for b := 2; b < perimeter/2; b += 2 { 108 | bSquared := b * b 109 | bsk := perimeter - b 110 | if bSquared%bsk != 0 { 111 | continue 112 | } 113 | 114 | k := bSquared / bsk 115 | if (bsk-k)%2 == 0 && bsk != k { 116 | a := (bsk - k) / 2 117 | c := perimeter - a - b 118 | triples := [3]int{a, b, c} 119 | if a > b { 120 | triples = [3]int{b, a, c} 121 | } 122 | if _, ok := seen[triples]; ok { 123 | continue 124 | } 125 | seen[triples] = true 126 | //fmt.Println(perimeter, a, b, c) 127 | perimeters[perimeter] += 1 128 | } 129 | } 130 | } 131 | 132 | fmt.Println("----------------") 133 | counts := 0 134 | for _, v := range perimeters { 135 | counts += 1 / v 136 | } 137 | 138 | fmt.Println(counts) 139 | } 140 | -------------------------------------------------------------------------------- /Problem_76_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | "math" 7 | "sort" 8 | "strconv" 9 | ) 10 | 11 | // https://projecteuler.net/problem=76 12 | 13 | func getPentagonalNumber(n int) int { 14 | return n * (3*n - 1) / 2 15 | } 16 | 17 | func computePartitions(goal int) []int { 18 | partitions := []int{1} 19 | for n := 1; n <= goal+1; n++ { 20 | partitions = append(partitions, 0) 21 | for k := 1; k <= n; k++ { 22 | coefficient := int(math.Pow(-1, float64(k+1))) 23 | for _, t := range []int{getPentagonalNumber(k), getPentagonalNumber(-k)} { 24 | if (n - t) >= 0 { 25 | partitions[n] += coefficient * partitions[n-t] 26 | } 27 | } 28 | } 29 | } 30 | return partitions 31 | } 32 | 33 | func main() { 34 | window := flag.Int("window", 100, "The window size") 35 | flag.Parse() 36 | 37 | partitions := computePartitions(*window) 38 | //https://en.wikipedia.org/wiki/Partition_function_(number_theory)#Recurrence_relations 39 | // We subtract 1 from the answer as it also includes the single value of window which is exempt in project euler 40 | fmt.Println(partitions) 41 | fmt.Println("************") 42 | fmt.Println(partitions[*window] - 1) 43 | 44 | } 45 | 46 | func getKey(n []int) string { 47 | result := "" 48 | for _, i := range n { 49 | result += "-" + strconv.Itoa(i) 50 | } 51 | 52 | return result 53 | } 54 | 55 | func bruteForce(n int) int { 56 | var starting []int 57 | for len(starting) < n { 58 | starting = append(starting, 1) 59 | } 60 | found := map[string]bool{} 61 | counters := map[int]int{} 62 | 63 | queue := make([][]int, 0) 64 | queue = append(queue, starting) 65 | for len(queue) > 0 { 66 | cur := queue[0] 67 | queue = queue[1:] 68 | fmt.Println(cur) 69 | if len(cur) == 1 || cur[0] != 1 { 70 | continue 71 | } 72 | counters[len(cur)] += 1 73 | 74 | for j := 1; j < len(cur); j++ { 75 | newCur := make([]int, len(cur)) 76 | copy(newCur, cur) 77 | newCur[j] += 1 78 | anotherCur := newCur[1:] 79 | sort.Ints(anotherCur) 80 | 81 | key := getKey(anotherCur) 82 | if _, ok := found[key]; ok { 83 | continue 84 | } 85 | found[key] = true 86 | 87 | queue = append(queue, anotherCur) 88 | } 89 | } 90 | 91 | fmt.Println(n, counters, len(found)) 92 | return len(found) 93 | } 94 | -------------------------------------------------------------------------------- /Problem_77_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | "math" 7 | ) 8 | 9 | // https://projecteuler.net/problem=77 10 | 11 | func primePartitions(n int, primes []int, currentIndex int, memo map[string]int) int { 12 | if n == 0 { 13 | return 1 14 | } 15 | 16 | if n < 0 { 17 | return 0 18 | } 19 | 20 | memoKey := fmt.Sprintf("%d-%d", n, currentIndex) 21 | if val, found := memo[memoKey]; found { 22 | return val 23 | } 24 | 25 | totalPartitions := 0 26 | for i := currentIndex; i < len(primes); i++ { 27 | prime := primes[i] 28 | totalPartitions += primePartitions(n-prime, primes, i, memo) 29 | } 30 | 31 | memo[memoKey] = totalPartitions 32 | return totalPartitions 33 | } 34 | 35 | func isPrime(n int) bool { 36 | i := 2 37 | for i <= int(math.Sqrt(float64(n))) { 38 | if n%i == 0 { 39 | return false 40 | } 41 | i++ 42 | } 43 | return true 44 | } 45 | 46 | func primePartitionsCount(n int, primes []int) int { 47 | memo := make(map[string]int) 48 | 49 | return primePartitions(n, primes, 0, memo) 50 | } 51 | 52 | func main() { 53 | window := flag.Int("window", 5000, "window size") 54 | flag.Parse() 55 | 56 | var primes []int 57 | for i := 2; i < *window; i++ { 58 | if isPrime(i) { 59 | primes = append(primes, i) 60 | } 61 | } 62 | 63 | for i := 2; i < math.MaxInt64; i++ { 64 | result := primePartitionsCount(i, primes) 65 | fmt.Println(i, result) 66 | if result > *window { 67 | fmt.Println(i) 68 | return 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /Problem_78_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | "math" 7 | "math/big" 8 | ) 9 | 10 | // https://projecteuler.net/problem=78 11 | 12 | func getPentagonalNumber(n int) int { 13 | return n * (3*n - 1) / 2 14 | } 15 | 16 | func computePartitions(goal int, divisor int) (int, *big.Int) { 17 | partitions := []*big.Int{big.NewInt(1)} 18 | 19 | for n := 1; n <= goal; n++ { 20 | partitions = append(partitions, new(big.Int)) 21 | for k := 1; k <= n; k++ { 22 | coefficient := int64(math.Pow(-1, float64(k+1))) 23 | for _, t := range []int{getPentagonalNumber(k), getPentagonalNumber(-k)} { 24 | if (n - t) >= 0 { 25 | partitions[n] = new(big.Int).Add(partitions[n], new(big.Int).Mul(big.NewInt(coefficient), partitions[n-t])) 26 | } 27 | } 28 | } 29 | 30 | currPartition := partitions[n] 31 | if new(big.Float).Quo(new(big.Float).SetInt(currPartition), big.NewFloat(float64(divisor))).IsInt() { 32 | return n, currPartition 33 | } 34 | } 35 | 36 | return 0, new(big.Int) 37 | } 38 | 39 | func main() { 40 | divisor := flag.Int("divisor", 1_000_000, "The window size") 41 | flag.Parse() 42 | 43 | fmt.Println(computePartitions(math.MaxInt64, *divisor)) 44 | } 45 | -------------------------------------------------------------------------------- /Problem_79_Euler/0079_keylog.txt: -------------------------------------------------------------------------------- 1 | 319 2 | 680 3 | 180 4 | 690 5 | 129 6 | 620 7 | 762 8 | 689 9 | 762 10 | 318 11 | 368 12 | 710 13 | 720 14 | 710 15 | 629 16 | 168 17 | 160 18 | 689 19 | 716 20 | 731 21 | 736 22 | 729 23 | 316 24 | 729 25 | 729 26 | 710 27 | 769 28 | 290 29 | 719 30 | 680 31 | 318 32 | 389 33 | 162 34 | 289 35 | 162 36 | 718 37 | 729 38 | 319 39 | 790 40 | 680 41 | 890 42 | 362 43 | 319 44 | 760 45 | 316 46 | 729 47 | 380 48 | 319 49 | 728 50 | 716 51 | -------------------------------------------------------------------------------- /Problem_79_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | "flag" 6 | "fmt" 7 | "log" 8 | "os" 9 | "sort" 10 | "strings" 11 | ) 12 | 13 | // https://projecteuler.net/problem=79 14 | 15 | func main() { 16 | fileName := flag.String("file", "0079_keylog.txt", "The name of the keylog file") 17 | flag.Parse() 18 | 19 | file, err := os.Open(*fileName) 20 | if err != nil { 21 | log.Fatal(err) 22 | } 23 | 24 | defer file.Close() 25 | 26 | numbers := map[string]map[string]bool{} 27 | scanner := bufio.NewScanner(file) 28 | for scanner.Scan() { 29 | line := scanner.Text() 30 | var arr []string 31 | for _, index := range line { 32 | if numbers[string(index)] == nil { 33 | numbers[string(index)] = map[string]bool{} 34 | } 35 | for _, d := range arr { 36 | numbers[string(index)][d] = true 37 | } 38 | arr = append(arr, string(index)) 39 | } 40 | } 41 | 42 | var digits []string 43 | for char, _ := range numbers { 44 | digits = append(digits, char) 45 | } 46 | 47 | fmt.Println(digits) 48 | fmt.Println(numbers) 49 | sort.Slice(digits, func(i, j int) bool { 50 | a, b := digits[i], digits[j] 51 | 52 | return len(numbers[a]) < len(numbers[b]) 53 | }) 54 | fmt.Println("**********") 55 | fmt.Println(strings.Join(digits, "")) 56 | } 57 | -------------------------------------------------------------------------------- /Problem_7_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | "math" 7 | ) 8 | 9 | // https://projecteuler.net/problem=7 10 | 11 | // We can offset unncessary computation by setting the prime check startpoint 12 | // using the prime count function 13 | // https://mathworld.wolfram.com/PrimeNumberTheorem.html 14 | // For simplicity, the table listed in the @findPrimeAtIndex function is used to approximate the occurrence 15 | // Additional study on implementing the code to generate the table is for the viewers discretion to do so 16 | 17 | 18 | // Not too efficient, overflows on n=17 19 | // Implements Wilson's theorem on prime validation 20 | // Implementation guide: https://codegolf.stackexchange.com/a/94385 21 | func primeCountingFunction(n int64, k int64, p int64) int{ 22 | count := 0 23 | for k <= n{ 24 | // A prime is valid if p%k == 1 25 | // and not if p%k == 0 26 | if p % k == 1 { 27 | count ++ 28 | } 29 | fmt.Println(k, p, count) 30 | 31 | p *= k * k 32 | k += 1 33 | } 34 | return count 35 | } 36 | 37 | 38 | func isPrime(n int) bool{ 39 | i := 2 40 | for i <= int(math.Sqrt(float64(n))) { 41 | if n % i == 0 { 42 | return false 43 | } 44 | i++ 45 | } 46 | return true 47 | } 48 | 49 | 50 | 51 | func findPrimeAtIndex(n int) int{ 52 | // Using prime counting function table values 53 | // Full table available here: https://mathworld.wolfram.com/PrimeCountingFunction.html 54 | // Each index here corresponds to a count up to 10 of the power of that index 55 | // 1 - 10, 2 -100, 3 - 1000 etc. 56 | primeCount := []int{4, 25, 168, 1229, 9592, 78498, 664579} 57 | availPrimeCount := 4 58 | nCountValue := 10 59 | 60 | for idx, num := range primeCount { 61 | if n < num{ 62 | break 63 | } 64 | availPrimeCount = num 65 | nCountValue = int(math.Pow(10, float64(idx+1))) 66 | } 67 | 68 | fmt.Println("Prime count, Current Value: ", availPrimeCount, nCountValue) 69 | 70 | for n > availPrimeCount { 71 | nCountValue++ 72 | if isPrime(nCountValue) { 73 | availPrimeCount++ 74 | } 75 | } 76 | 77 | return nCountValue 78 | } 79 | 80 | func main(){ 81 | maxNumPtr := flag.Int("number", 10001, "Integer for the max range") 82 | flag.Parse() 83 | fmt.Println("Prime is ", findPrimeAtIndex(*maxNumPtr)) 84 | } 85 | 86 | 87 | -------------------------------------------------------------------------------- /Problem_80_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | "math/big" 7 | "strings" 8 | ) 9 | 10 | // https://projecteuler.net/problem=79 11 | 12 | // Use main.py as golang has precision issues 13 | func main() { 14 | window := flag.Int("window", 100, "The window size") 15 | flag.Parse() 16 | 17 | prec := uint(200) 18 | total := 0 19 | for i := 0; i <= *window; i++ { 20 | val := new(big.Float).Sqrt(big.NewFloat(float64(i)).SetPrec(100)).SetPrec(prec) 21 | newVal := fmt.Sprintf("%.100f", val) 22 | dValue := strings.Split(newVal, ".")[1] 23 | fmt.Println(dValue) 24 | for _, char := range strings.TrimSpace(dValue) { 25 | fmt.Println(string(char), int(char-'0')) 26 | total += int(char - '0') 27 | } 28 | } 29 | 30 | fmt.Println(total) 31 | } 32 | -------------------------------------------------------------------------------- /Problem_80_Euler/main.py: -------------------------------------------------------------------------------- 1 | from decimal import Decimal, localcontext 2 | 3 | def prob80(): 4 | total = 0 5 | for x in range(1,100): 6 | with localcontext() as ctx: 7 | ctx.prec = 105 8 | if len(str(Decimal(x).sqrt())) == 1: 9 | total+=0 10 | else: 11 | a = sum([int(i) for i in str(Decimal(x).sqrt())[2:101]])+int(str(Decimal(x).sqrt())[0]) 12 | total+=a 13 | return total 14 | print(prob80()) -------------------------------------------------------------------------------- /Problem_81_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | // https://projecteuler.net/problem=18 4 | 5 | import ( 6 | "bufio" 7 | "flag" 8 | "fmt" 9 | "os" 10 | "strconv" 11 | "strings" 12 | ) 13 | 14 | func DFS(arr [][]int) int { 15 | for i := len(arr[len(arr)-1]) - 2; i >= 0; i-- { 16 | for j := 0; j <= i; j++ { 17 | if arr[i+1][j] > arr[i+1][j+1] { 18 | arr[i][j] += arr[i+1][j] 19 | } else { 20 | arr[i][j] += arr[i+1][j+1] 21 | } 22 | } 23 | } 24 | return arr[0][0] 25 | } 26 | 27 | func main() { 28 | 29 | fileName := flag.String("file", "0081_matrix.txt", "File to read integers from") 30 | flag.Parse() 31 | 32 | input, err := os.Open(*fileName) 33 | if err != nil { 34 | panic(err) 35 | } 36 | defer input.Close() 37 | 38 | buffer := bufio.NewScanner(input) 39 | var stringArr []string 40 | var triangleArr [][]int 41 | for buffer.Scan() { 42 | var numArr []int 43 | stringArr = strings.Split(strings.Trim(buffer.Text(), " "), ",") 44 | for _, el := range stringArr { 45 | val, _ := strconv.Atoi(el) 46 | numArr = append(numArr, val) 47 | } 48 | triangleArr = append(triangleArr, numArr) 49 | } 50 | fmt.Println(len(triangleArr[0])) 51 | result := DFS(triangleArr) 52 | fmt.Println(result) 53 | } 54 | -------------------------------------------------------------------------------- /Problem_8_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "math" 5 | "fmt" 6 | "flag" 7 | "os" 8 | "strconv" 9 | ) 10 | 11 | // https://projecteuler.net/problem=8 12 | 13 | 14 | func getSliceProduct(elems []string) int{ 15 | result := 1 16 | for _, i := range elems { 17 | temp, err := strconv.Atoi(i) 18 | if err != nil{ 19 | fmt.Println("Element is not integer ", i, ", ignored during loop run") 20 | } 21 | result *= temp 22 | } 23 | return result 24 | } 25 | 26 | 27 | func loopAcrossValueSets(elemStr string, window int) int{ 28 | i := 0 29 | elems := []string{} 30 | for i, _ := range elemStr { 31 | elems = append(elems, string(elemStr[i])) 32 | } 33 | result := math.MinInt64 34 | fmt.Println(elems) 35 | for i < (len(elems) - window) { 36 | temp := getSliceProduct(elems[i:i+window]) 37 | if temp > result { 38 | result = temp 39 | } 40 | i++ 41 | } 42 | return result 43 | } 44 | 45 | func main(){ 46 | content, err := os.ReadFile("number.txt") 47 | if err != nil { 48 | panic(err) 49 | } 50 | elems := flag.String("elems", string(content), "Integer element to run the product over") 51 | window := flag.Int("window", 13, "Integer for the max product window") 52 | flag.Parse() 53 | fmt.Println(loopAcrossValueSets(*elems, *window)) 54 | 55 | } 56 | 57 | -------------------------------------------------------------------------------- /Problem_8_Euler/number.txt: -------------------------------------------------------------------------------- 1 | 7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450 -------------------------------------------------------------------------------- /Problem_9_Euler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | //https://projecteuler.net/problem=9 4 | 5 | 6 | import ( 7 | "fmt" 8 | "math" 9 | "flag" 10 | ) 11 | 12 | func BinetFormula(n float64) float64 { 13 | sqrt5 := math.Sqrt(5) 14 | phi := (1 + sqrt5) / 2 15 | ans := math.Round(math.Pow(phi, n) / sqrt5) 16 | fmt.Printf("Value at n: %f in fibonnaci sequence is: %f\n", n, ans) 17 | return ans 18 | } 19 | 20 | func getTriple(n float64) [3]float64{ 21 | firstTriple := BinetFormula(n) * BinetFormula(n+3) 22 | secondTriple := BinetFormula(n+1) * BinetFormula(n+2) * 2 23 | thirdTriple := math.Pow(BinetFormula(n+1), 2) + math.Pow(BinetFormula(n+2), 2) 24 | return [...]float64{firstTriple, secondTriple, thirdTriple} 25 | } 26 | 27 | 28 | func validateConditionals(maxSum float64, firstTriple float64, secondTriple float64, thirdTriple float64) bool{ 29 | return math.Pow(firstTriple, 2) + math.Pow(secondTriple, 2) == math.Pow(thirdTriple, 2) && firstTriple + secondTriple + thirdTriple == maxSum 30 | 31 | } 32 | 33 | func getPythagoreanTriple(maxSum float64) [3]float64 { 34 | var n float64 = 0 35 | for n < math.Sqrt(maxSum){ 36 | triples := getTriple(n) 37 | firstTriple := triples[0] 38 | secondTriple := triples[1] 39 | thirdTriple := triples[2] 40 | if validateConditionals(maxSum, firstTriple, secondTriple, thirdTriple) { 41 | return getTriple(n) 42 | } 43 | n++ 44 | } 45 | return [...]float64{0, 0, 0} 46 | } 47 | 48 | func getPythagoreanTripleSquared(maxSum float64) [3]float64 { 49 | var n float64 = 0 50 | for n < math.Sqrt(maxSum){ 51 | firstTriple := 2 * n 52 | secondTriple := math.Pow(n, 2) - 1 53 | thirdTriple := math.Pow(n, 2) + 1 54 | if validateConditionals(maxSum, firstTriple, secondTriple, thirdTriple) { 55 | return [...]float64 {firstTriple, secondTriple, thirdTriple} 56 | } 57 | n++ 58 | } 59 | return [...]float64{0, 0, 0} 60 | } 61 | 62 | 63 | func getPythagoreanTripleBruteForce(n float64) [3]float64{ 64 | var i float64 = 1 65 | var j float64 = 0 66 | var k float64 = 0 67 | for i < n { 68 | j = 0 69 | for j < n { 70 | k = n - i - j 71 | 72 | // fmt.Println("Using the following values: ", i, j, k, n) 73 | if validateConditionals(n, i, j, k) { 74 | return [...]float64 {i, j, k} 75 | } 76 | j++ 77 | } 78 | i++ 79 | } 80 | return [...]float64{0, 0, 0} 81 | } 82 | 83 | 84 | func main(){ 85 | maxNumPtr := flag.Float64("number", 1000, "Integer for the max range") 86 | flag.Parse() 87 | solution := getPythagoreanTripleBruteForce(*maxNumPtr) 88 | 89 | fmt.Println("Product array is ", solution) 90 | fmt.Println("Answer is: ", int(solution[0] * solution[1] * solution[2])) 91 | } 92 | 93 | 94 | -------------------------------------------------------------------------------- /Product_Of_Array_Except_Itself/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | // https://leetcode.com/problems/product-of-array-except-self/ 4 | 5 | func productExceptSelf(nums []int) []int { 6 | arr := make([]int, len(nums)) 7 | p := 1 8 | for idx, el := range nums { 9 | arr[idx] = 1 10 | arr[idx] *= p 11 | p *= el 12 | } 13 | 14 | p = 1 15 | for idx := len(nums) - 1; idx >= 0; idx-- { 16 | arr[idx] *= p 17 | p *= nums[idx] 18 | } 19 | return arr 20 | } 21 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # algoexpert-solutions 2 | REPO containing code solutions for algo-expert problems, solved in Go to solidify language skills 3 | -------------------------------------------------------------------------------- /Regular_Expression_Matching/main.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | /* match: search for regexp anywhere in text */ 4 | int match(char *regexp, char *text) { 5 | if (regexp[0] == '^') 6 | return matchhere(regexp + 1, text); 7 | do { /* must look even if string is empty */ 8 | if (matchhere(regexp, text)) 9 | return 1; 10 | } while (*text++ != '\0'); 11 | return 0; 12 | } 13 | 14 | /* matchhere: search for regexp at beginning of text */ 15 | int matchhere(char *regexp, char *text) { 16 | if (regexp[0] == '\0') 17 | return 1; 18 | if (regexp[1] == '*') 19 | return matchstar(regexp[0], regexp + 2, text); 20 | if (regexp[0] == '$' && regexp[1] == '\0') 21 | return *text == '\0'; 22 | if (*text != '\0' && (regexp[0] == '.' || regexp[0] == *text)) 23 | return matchhere(regexp + 1, text + 1); 24 | return 0; 25 | } 26 | 27 | /* matchstar: search for c*regexp at beginning of text */ 28 | int matchstar(int c, char *regexp, char *text) { 29 | do { /* a * matches zero or more instances */ 30 | if (matchhere(regexp, text)) 31 | return 1; 32 | } while (*text != '\0' && (*text++ == c || c == '.')); 33 | return 0; 34 | } 35 | 36 | int main() { printf("%d", match("ab", "aa")); } 37 | -------------------------------------------------------------------------------- /Regular_Expression_Matching/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | -------------------------------------------------------------------------------- /Single_Cycle_Check/main.go: -------------------------------------------------------------------------------- 1 | package Single_Cycle_Check 2 | 3 | 4 | // https://www.algoexpert.io/questions/Single%20Cycle%20Check 5 | 6 | func modLikePython(d int, m int) int { 7 | var res int = d % m 8 | if ((res < 0 && m > 0) || (res > 0 && m < 0)) { 9 | return res + m 10 | } 11 | return res 12 | } 13 | 14 | 15 | // O(n) time and space 16 | func HasSingleCycle(array []int) bool { 17 | // Write your code here. 18 | visited := make([]bool, len(array)) 19 | curr_idx := 0 20 | num_el_visited := 0 21 | for num_el_visited < len(array){ 22 | curr_idx = modLikePython(curr_idx + array[curr_idx], len(array)) 23 | if visited[curr_idx]{ 24 | return false 25 | } 26 | visited[curr_idx] = true 27 | num_el_visited += 1 28 | } 29 | return curr_idx == 0 30 | } 31 | 32 | 33 | // Optimised Version 34 | // O(n) time 35 | // O(1) space 36 | func HasSingleCycle(array []int) bool { 37 | curr_idx := 0 38 | num_el_visited := 0 39 | for num_el_visited < len(array){ 40 | if num_el_visited > 0 && curr_idx == 0{ 41 | return false 42 | } 43 | curr_idx = modLikePython(curr_idx + array[curr_idx], len(array)) 44 | num_el_visited += 1 45 | } 46 | return curr_idx == 0 47 | } -------------------------------------------------------------------------------- /Smallest_Difference/main.go: -------------------------------------------------------------------------------- 1 | package Smallest_Difference 2 | 3 | import ( 4 | "sort" 5 | "math" 6 | ) 7 | 8 | // https://www.algoexpert.io/questions/Smallest%20Difference 9 | 10 | // Brute Force O(mn) 11 | // n - len(array1) 12 | // m - len(array2) 13 | func SmallestDifference(array1 []int, array2 []int) []int { 14 | sort.Ints(array1) 15 | sort.Ints(array2) 16 | arr, diff := []int{}, math.Inf(1) 17 | 18 | for _, num := range array1 { 19 | for _, num2 := range array2 { 20 | if math.Abs(float64(num - num2)) < diff { 21 | diff = math.Abs(float64(num - num2)) 22 | arr = []int{num, num2} 23 | } 24 | } 25 | } 26 | 27 | return arr 28 | } 29 | 30 | 31 | // Optimised version O(nlogn + mlogm) 32 | // n - len(array1) 33 | // m - len(array2) 34 | func SmallestDifference(array1 []int, array2 []int) []int { 35 | // Write your code here. 36 | sort.Ints(array1) 37 | sort.Ints(array2) 38 | arr, diff := []int{}, math.MaxInt64 39 | idx1, idx2, current := 0, 0, 0 40 | for idx1 < len(array1) && idx2 < len(array2){ 41 | first, second := array1[idx1], array2[idx2] 42 | if first > second { 43 | current = first - second 44 | idx2+=1 45 | } else if second > first { 46 | current = second - first 47 | idx1+=1 48 | } else { 49 | return []int{first, second} 50 | } 51 | if diff > current{ 52 | diff = current 53 | arr = []int{first, second} 54 | } 55 | } 56 | 57 | return arr 58 | } -------------------------------------------------------------------------------- /Subets/main.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | # https://leetcode.com/problems/subsets/ 4 | 5 | # O(n * 2^n) 6 | class Solution(object): 7 | def subsets(self, nums): 8 | """ 9 | :type nums: List[int] 10 | :rtype: List[List[int]] 11 | """ 12 | arr = [] 13 | for i in range(0, pow(2, len(nums))): 14 | val = format(i, "#0{}b".format(len(nums)+2)).replace('0b', '') 15 | print(val) 16 | temp = [x[1] for x in zip(val, nums) if x[0] == '1'] 17 | arr.append(temp) 18 | return arr 19 | 20 | 21 | 22 | 23 | [1, 2, 3, 4, 5] 24 | 25 | 26 | 1 - 0 0 0 0 1 27 | -------------------------------------------------------------------------------- /Three_Number_Sum/main.go: -------------------------------------------------------------------------------- 1 | package Three_Number_Sum 2 | 3 | 4 | import ( 5 | "math" 6 | "sort" 7 | ) 8 | 9 | 10 | // https://www.algoexpert.io/questions/Three%20Number%20Sum 11 | 12 | func SumPow10(num int, num2 int, num3 int) int64 { 13 | return int64(math.Pow10(num) + math.Pow10(num2) + math.Pow10(num3)) 14 | } 15 | 16 | func Find(slice []int64, val int64) bool { 17 | for _, item := range slice { 18 | if item == val { 19 | return true 20 | } 21 | } 22 | return false 23 | } 24 | 25 | //Brute force O(mn3) 26 | // m - Number of unique triplet combinations 27 | // n - Number of elements in each array, equal sized 28 | func ThreeNumberSum(array []int, target int) [][]int { 29 | sort.Ints(array) 30 | arr := [][]int{} 31 | var sums []int64 32 | for _, num := range array { 33 | for _, num2 := range array{ 34 | for _, num3 := range array{ 35 | sum := num + num2 + num3 36 | sumpow10 := SumPow10(num, num2, num3) 37 | if sum == target && !Find(sums, sumpow10) && num != num2 && num != num3 && num2 != num3{ 38 | sums = append(sums, sumpow10) 39 | arr = append(arr, []int{num, num2, num3}) 40 | } 41 | } 42 | } 43 | } 44 | return arr 45 | } 46 | 47 | 48 | //Optimised version O(nlogn) 49 | func ThreeNumberSum(array []int, target int) [][]int { 50 | sort.Ints(array) 51 | triplets := [][]int{} 52 | for idx, num := range array { 53 | left, right := idx+1, len(array) - 1; 54 | for left < right { 55 | currentSum := num + array[left] + array[right] 56 | if currentSum == target{ 57 | triplets = append(triplets, []int{num, array[left], array[right]}) 58 | left += 1 59 | right -= 1 60 | } else if currentSum > target{ 61 | right -= 1 62 | } else if currentSum < target{ 63 | left += 1 64 | } 65 | } 66 | } 67 | return triplets 68 | } -------------------------------------------------------------------------------- /Two_City_Scheduling/main.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | # https://leetcode.com/problems/two-city-scheduling/ 4 | 5 | # Two City Scheduling 6 | class Solution(object): 7 | def twoCitySchedCost(self, costs): 8 | """ 9 | :type costs: List[List[int]] 10 | :rtype: int 11 | """ 12 | cost = 0 13 | costs = sorted(costs, key = lambda x: x[0] - x[1]) 14 | avg = len(costs) / 2 15 | cost += sum([x[0] for x in costs[:avg]]) 16 | cost += sum([x[1] for x in costs[avg:]]) 17 | return cost 18 | 19 | -------------------------------------------------------------------------------- /Word_Ladder_II/.main.go.swp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tiemma/algorithm-solutions/b259be686f62302d12f508eb798d5444bfdd3b37/Word_Ladder_II/.main.go.swp -------------------------------------------------------------------------------- /Zigzag_Conversion/main.go: -------------------------------------------------------------------------------- 1 | package convert 2 | 3 | // https://leetcode.com/problems/zigzag-conversion/ 4 | 5 | import ( 6 | "strings" 7 | ) 8 | 9 | func convert(s string, numRows int) string { 10 | if numRows == 1{ 11 | return s 12 | } 13 | 14 | arr := make([]string, numRows) 15 | cord := 0 16 | factor := 1 17 | for _, val := range s{ 18 | arr[cord] += string(val) 19 | if cord == numRows - 1 { 20 | factor = -1 21 | } else if cord == 0 { 22 | factor = 1 23 | } 24 | cord += factor 25 | } 26 | return strings.Join(arr, "") 27 | 28 | } 29 | -------------------------------------------------------------------------------- /Zigzag_Conversion/main.py: -------------------------------------------------------------------------------- 1 | 2 | # https://leetcode.com/problems/zigzag-conversion/ 3 | 4 | class Solution: 5 | def convert(self, s: str, numRows: int) -> str: 6 | if numRows == 1: 7 | return s 8 | arr = {} 9 | for i in range(numRows): 10 | arr[i] = "" 11 | cord = 0 12 | const = 1 13 | reset = True 14 | for string in s: 15 | arr[cord] += string 16 | if cord == numRows - 1: 17 | const = -1 18 | elif cord == 0: 19 | const = 1 20 | cord += const 21 | result = "" 22 | for i in arr: 23 | result += arr[i] 24 | return result 25 | 26 | 27 | 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/tiemma/algorithm-solutions 2 | 3 | go 1.20 4 | 5 | require gonum.org/v1/plot v0.15.0 6 | 7 | require ( 8 | git.sr.ht/~sbinet/gg v0.6.0 // indirect 9 | github.com/ajstarks/svgo v0.0.0-20211024235047-1546f124cd8b // indirect 10 | github.com/campoy/embedmd v1.0.0 // indirect 11 | github.com/go-fonts/liberation v0.3.3 // indirect 12 | github.com/go-latex/latex v0.0.0-20240709081214-31cef3c7570e // indirect 13 | github.com/go-pdf/fpdf v0.9.0 // indirect 14 | github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 // indirect 15 | github.com/pmezard/go-difflib v1.0.0 // indirect 16 | golang.org/x/image v0.21.0 // indirect 17 | golang.org/x/text v0.19.0 // indirect 18 | ) 19 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | git.sr.ht/~sbinet/cmpimg v0.1.0 h1:E0zPRk2muWuCqSKSVZIWsgtU9pjsw3eKHi8VmQeScxo= 2 | git.sr.ht/~sbinet/gg v0.6.0 h1:RIzgkizAk+9r7uPzf/VfbJHBMKUr0F5hRFxTUGMnt38= 3 | git.sr.ht/~sbinet/gg v0.6.0/go.mod h1:uucygbfC9wVPQIfrmwM2et0imr8L7KQWywX0xpFMm94= 4 | github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= 5 | github.com/ajstarks/deck v0.0.0-20200831202436-30c9fc6549a9/go.mod h1:JynElWSGnm/4RlzPXRlREEwqTHAN3T56Bv2ITsFT3gY= 6 | github.com/ajstarks/deck/generate v0.0.0-20210309230005-c3f852c02e19/go.mod h1:T13YZdzov6OU0A1+RfKZiZN9ca6VeKdBdyDV+BY97Tk= 7 | github.com/ajstarks/svgo v0.0.0-20211024235047-1546f124cd8b h1:slYM766cy2nI3BwyRiyQj/Ud48djTMtMebDqepE95rw= 8 | github.com/ajstarks/svgo v0.0.0-20211024235047-1546f124cd8b/go.mod h1:1KcenG0jGWcpt8ov532z81sp/kMMUG485J2InIOyADM= 9 | github.com/campoy/embedmd v1.0.0 h1:V4kI2qTJJLf4J29RzI/MAt2c3Bl4dQSYPuflzwFH2hY= 10 | github.com/campoy/embedmd v1.0.0/go.mod h1:oxyr9RCiSXg0M3VJ3ks0UGfp98BpSSGr0kpiX3MzVl8= 11 | github.com/go-fonts/dejavu v0.3.4 h1:Qqyx9IOs5CQFxyWTdvddeWzrX0VNwUAvbmAzL0fpjbc= 12 | github.com/go-fonts/latin-modern v0.3.3 h1:g2xNgI8yzdNzIVm+qvbMryB6yGPe0pSMss8QT3QwlJ0= 13 | github.com/go-fonts/liberation v0.3.3 h1:tM/T2vEOhjia6v5krQu8SDDegfH1SfXVRUNNKpq0Usk= 14 | github.com/go-fonts/liberation v0.3.3/go.mod h1:eUAzNRuJnpSnd1sm2EyloQfSOT79pdw7X7++Ri+3MCU= 15 | github.com/go-latex/latex v0.0.0-20240709081214-31cef3c7570e h1:xcdj0LWnMSIU1j8+jIeJyfvk6SjgJedFQssSqFthJ2E= 16 | github.com/go-latex/latex v0.0.0-20240709081214-31cef3c7570e/go.mod h1:J4SAGzkcl+28QWi7yz72tyC/4aGnppOvya+AEv4TaAQ= 17 | github.com/go-pdf/fpdf v0.9.0 h1:PPvSaUuo1iMi9KkaAn90NuKi+P4gwMedWPHhj8YlJQw= 18 | github.com/go-pdf/fpdf v0.9.0/go.mod h1:oO8N111TkmKb9D7VvWGLvLJlaZUQVPM+6V42pp3iV4Y= 19 | github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 h1:DACJavvAHhabrF08vX0COfcOBJRhZ8lUbR+ZWIs0Y5g= 20 | github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0/go.mod h1:E/TSTwGwJL78qG/PmXZO1EjYhfJinVAhrmmHX6Z8B9k= 21 | github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= 22 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 23 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 24 | github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= 25 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 26 | golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= 27 | golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= 28 | golang.org/x/exp v0.0.0-20241009180824-f66d83c29e7c h1:7dEasQXItcW1xKJ2+gg5VOiBnqWrJc+rq0DPKyvvdbY= 29 | golang.org/x/image v0.21.0 h1:c5qV36ajHpdj4Qi0GnE0jUc/yuo33OLFaa0d+crTD5s= 30 | golang.org/x/image v0.21.0/go.mod h1:vUbsLavqK/W303ZroQQVKQ+Af3Yl6Uz1Ppu5J/cLz78= 31 | golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= 32 | golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= 33 | golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= 34 | golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= 35 | golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 36 | golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 37 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 38 | golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 39 | golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 40 | golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 41 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 42 | golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= 43 | golang.org/x/text v0.19.0 h1:kTxAhCbGbxhK0IwgSKiMO5awPoDQ0RpfiVYBfK860YM= 44 | golang.org/x/text v0.19.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY= 45 | golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= 46 | golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= 47 | golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0= 48 | golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 49 | golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 50 | golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 51 | gonum.org/v1/gonum v0.15.1 h1:FNy7N6OUZVUaWG9pTiD+jlhdQ3lMP+/LcTpJ6+a8sQ0= 52 | gonum.org/v1/plot v0.15.0 h1:SIFtFNdZNWLRDRVjD6CYxdawcpJDWySZehJGpv1ukkw= 53 | gonum.org/v1/plot v0.15.0/go.mod h1:3Nx4m77J4T/ayr/b8dQ8uGRmZF6H3eTqliUExDrQHnM= 54 | honnef.co/go/tools v0.1.3/go.mod h1:NgwopIslSNH47DimFoV78dnkksY2EFtX0ajyb3K/las= 55 | rsc.io/pdf v0.1.1 h1:k1MczvYDUvJBe93bYd7wrZLLUEcLZAuF824/I4e5Xr4= 56 | --------------------------------------------------------------------------------