Skip to content
loading...

re: Write a script to find "Perfect Numbers" VIEW POST

FULL DISCUSSION
 

I wrote this script 3 years ago.

def perfect_number(num):
    su = 0
    for i in range(1, num):
        if num % i == 0:
            su += i
    return su == num

def perfect_number_main(n):
    if perfect_number(n) == True:
        print("%s is perfect" % n)
    else:
        pass

for i in range(1,10000):
    perfect_number_main(i)
 

How efficient do you remember this article being?

 

Translate yours in Ruby.

def sum_divisions(n)
  (1...n).select{|i| n % i == 0}.sum
end

def perfect_number?(n)
  n == sum_divisions(n)
end

(1..10_000).each do |i|
  puts "#{i} is perfect" if perfect_number?(i)
end

 

What do you do with a holy lot of time you saved by writing resu instead of result?

:)

Local can be short, may be r is better.

Clear and ASAP.

 

In JS, not so good cause I'm new to JS. If any good writing comment please.

const sum = (accumulator, currentValue) => accumulator + currentValue;

function range(size, startAt = 0) {
  return [...Array(size).keys()].map(i => i + startAt);
}

function sumDivisions(n){
  arr = range(n-1, startAt=1).filter(x => n % x == 0)
  return arr.reduce(sum, 0);
}

function is_perfect_number(n){
  return sumDivisions(n) == n
}

range(10000, 1).forEach(function(x){
  if(is_perfect_number(x)){
    console.log(x);
  }
})
 

Do you have a better version for Go?

package main

import (
  "fmt"
)

func sum_divisions(n int) int {
  sum := 0
  for i := 1; i < n; i++ {
    if n % i == 0 {
      sum += i
    }
  }
  return sum
}

func is_perfect(n int) bool {
  return n == sum_divisions(n)
}

func main() {
  for i := 1; i <= 10000; i++ {
    if is_perfect(i) {
      fmt.Println(i)
    }
  }
}

code of conduct - report abuse