Created
June 4, 2016 12:31
-
-
Save harrysbaraini/6f3b42ffa53c4d7e0960c34967831204 to your computer and use it in GitHub Desktop.
Golang - simple math examples
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
) | |
func calculateCollatz(n int) int { | |
current := 1 | |
for n > 1 { | |
current++ | |
if n%2 == 0 { | |
n = n/2 | |
} else { | |
n = 3*n + 1 | |
} | |
} | |
return current | |
} | |
func main() { | |
fmt.Println("Calculando Conjectura de Collatz dos inteiros positivos até 999999") | |
fmt.Println("O resultado final apresentará qual item possui a maior sequencia de itens\n") | |
var bigger struct { | |
Number int | |
Total int | |
} | |
bigger.Number = 0 | |
bigger.Total = 0 | |
n := 1 | |
for n < 999999 { | |
current := calculateCollatz(n) | |
if bigger.Total < current { | |
bigger.Number = n | |
bigger.Total = current | |
} | |
n++ | |
} | |
fmt.Printf("n=%d resulta em %d itens\n", bigger.Number, bigger.Total) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
// Subcadeia da soma máxima | |
// ---------------------------- | |
// Dado um conjunto de números, descobrir o subconjunto em que a soma dos elementos são de máxima soma. | |
// Exemplo: dado o conjunto de elementos [2, -4, 6, 8, -10, 100, -6, 5] | |
// O subconjunto de soma máxima é: [2, -4, **6, 8, -10, 100**, -6, 5] | |
// Assim, o programa deve retornar a posição do primeiro e do último elemento da subcadeia. Neste exemplo, as posições 2 e 5, considerando a primeira posição com índice 0. | |
import "fmt" | |
func main() { | |
var resultSet struct{ | |
Sum int | |
Start int | |
End int | |
} | |
resultSet.Sum = 0 | |
resultSet.Start = 0 | |
resultSet.End = 0 | |
elementSet := []int{2, -4, 6, 8, -10, 100, -6, 5} | |
// elementSet := []int{1, -1, -3, 2, 2, -2, 1, -1} | |
for i := 0; i < len(elementSet); i++ { | |
res := elementSet[i] | |
for n := i+1; n < len(elementSet); n++ { | |
res += elementSet[n] | |
if res > resultSet.Sum { | |
resultSet.Sum = res | |
resultSet.Start = i | |
resultSet.End = n | |
} | |
} | |
} | |
fmt.Printf("O subconjunto com a maior resposta(%d) está entre [ %d : %d ]\n", resultSet.Sum, resultSet.Start, resultSet.End) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment