How to resolve the algorithm Perfect numbers step by step in the CoffeeScript programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Perfect numbers step by step in the CoffeeScript programming language
Table of Contents
Problem Statement
Write a function which says whether a number is perfect.
A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself. Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Note: The faster Lucas-Lehmer test is used to find primes of the form 2n-1, all known perfect numbers can be derived from these primes using the formula (2n - 1) × 2n - 1. It is not known if there are any odd perfect numbers (any that exist are larger than 102000). The number of known perfect numbers is 51 (as of December, 2018), and the largest known perfect number contains 49,724,095 decimal digits.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Perfect numbers step by step in the CoffeeScript programming language
Source code in the coffeescript programming language
is_perfect_number = (n) ->
do_factors_add_up_to n, 2*n
do_factors_add_up_to = (n, desired_sum) ->
# We mildly optimize here, by taking advantage of
# the fact that the sum_of_factors( (p^m) * x)
# is (1 + ... + p^m-1 + p^m) * sum_factors(x) when
# x is not itself a multiple of p.
p = smallest_prime_factor(n)
if p == n
return desired_sum == p + 1
# ok, now sum up all powers of p that
# divide n
sum_powers = 1
curr_power = 1
while n % p == 0
curr_power *= p
sum_powers += curr_power
n /= p
# if desired_sum does not divide sum_powers, we
# can short circuit quickly
return false unless desired_sum % sum_powers == 0
# otherwise, recurse
do_factors_add_up_to n, desired_sum / sum_powers
smallest_prime_factor = (n) ->
for i in [2..n]
return n if i*i > n
return i if n % i == 0
# tests
do ->
# This is pretty fast...
for n in [2..100000]
console.log n if is_perfect_number n
# For big numbers, let's just sanity check the known ones.
known_perfects = [
33550336
8589869056
137438691328
]
for n in known_perfects
throw Error("fail") unless is_perfect_number(n)
throw Error("fail") if is_perfect_number(n+1)
You may also check:How to resolve the algorithm Smarandache prime-digital sequence step by step in the Raku programming language
You may also check:How to resolve the algorithm Comments step by step in the OxygenBasic programming language
You may also check:How to resolve the algorithm Boolean values step by step in the zkl programming language
You may also check:How to resolve the algorithm Longest common substring step by step in the JavaScript programming language
You may also check:How to resolve the algorithm Reverse a string step by step in the OxygenBasic programming language