Advertisement
xah

0012 - Project Euler

xah
Nov 23rd, 2021
1,189
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // 0012.go contains some functions to solve ProjectEuler.net's Problem #12
  2. // https://projecteuler.net/problem=12
  3. package main
  4.  
  5. import "fmt"
  6.  
  7. // CountDivisors returns the count of possible divisors of a given number,
  8. // including 1 and itself.
  9. func CountDivisors(number int) int {
  10.     count := 0
  11.     max := number/2
  12.  
  13.     for i := 1; i < max; i++ {
  14.         if number%i == 0 {
  15.             // Increase count by itself + value (number / i)
  16.             count += 2;
  17.  
  18.             // Update max number
  19.             max = number / i
  20.         }
  21.     }
  22.  
  23.     // Return count
  24.     return count
  25. }
  26.  
  27. // FirstTriangularNumber returns the first triangular number with more
  28. // that the given number of divisors.
  29. func FirstTriangularNumber(numDivisors int) int {
  30.     triangularnumber := 0
  31.     count := 0
  32.  
  33.     for i := 1; count <= numDivisors; i++ {
  34.         // Generate triangular number
  35.         triangularnumber += i
  36.  
  37.         // Update divisor count to divisors in current triangular number
  38.         count = CountDivisors(triangularnumber)
  39.     }
  40.  
  41.     // Return triangular number
  42.     return triangularnumber
  43. }
  44.  
  45. func main(){
  46.     // Display result
  47.     fmt.Println(FirstTriangularNumber(500))
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement