Numbers and your friends

Asked

Viewed 751 times

26

The sum of all natural numbers (positive integer) of divisors 220 except 220 is equal to:

1 + 2 + 4 + 5 + 10 + 11 + 20 + 22 + 44 + 55 + 110 = 284

And the sum of all natural numbers of divisors 284 except himself is equal to:

1 + 2 + 4 + 71 + 142 = 220

The numbers 220 and 284 are called Friends. Generally, we say that two positive integers are Friends if each of the sum of its divisors (excluding the number itself) is equal to the other number.

Write the program to calculate all numbers Friends from 2 to N.

Example:

If the entrance is N = 1500 the output should be: (284, 220), (1210, 1184)

Note: Use the language you prefer.

  • 4

    For those who are negative, please read here: https://pt.meta.stackoverflow.com/questions/1366/desafios-e-code-golf

  • 1

    In general, you will need a function that returns a list of the divisors of a given number, another that returns the sum of the values of a list, and for each number from 2 to N, it will take the list of divisors, add to get a "candidate for Friend"then take the candidate’s divisor list and add to compare with the original.

  • 1

    @Haroldo_ok yes, but do you know what Code Golf is? The challenge is to write a program that manages this result with as few characters as possible.

6 answers

21


Python (115 bytes)

N,d=1500,lambda n:sum(i for i in range(1,n) if n%i==0)
print({i:d(i) for i in range(N+1) if i==d(d(i)) and i>d(i)})

Exit:

{284: 220, 1210: 1184}

Explanation:

In the first line the values of N, 1500, and d, a function lambda calculating the sum of the divisors of a value n. In the second line, the syntax of Dict comprehension, returning the pair i: d(i) for all the value of i equal to d(d(i)) and that it is greater than d(i), in the range defined by range(2,N+1). The very condition i>d(i) already eliminates duplicate pairs such as (284, 220) and (220, 284) and pairs composed of perfect numbers such as (6, 6) and (28, 28), which satisfy the condition i == d(d(i)).

See working on Ideone.

17

C# (LINQ way) 284 bytes

Disclaimer: It will only work on interactive consoles, like Linqpad or C# Interactive Visual Studio, because no public class was defined for the method Main()

static int d(int n) => Enumerable.Range(1, n-1).Where(i => n % i == 0).Sum();   
void Main()
{
    int N = 1500;       
    var q = from e in Enumerable.Range(2, N-1)
            let k = d(d(e))
            let v = d(e)
            where e == k && e > v
            select new {k,v};

    foreach(var a in q) Console.WriteLine(a);
}

Code on Github for future reference

Output (default form for anonymous objects):

{ v = 284, x = 220 }
{ v = 1210, x = 1184 }

Explanation:

Defines the variable N with the desired value (1500), d as a method (Expression bodied Function) calculating the sum of all divisors of n, excluding himself. The query LINQ traverses the entire list of N values reducing it to a list of anonymous objects with the friend numbers.

17

Javascript ES6 (153 bytes)

N=1500,d=n=>[...Array(n).keys()].reduce((s,i)=>n%i==0?s+i:s,0);alert([...Array(N+1).keys()].reduce((v,i)=>i==d(d(i))&&i>d(i)?v.concat([[i,d(i)]]):v,[]));

Exit:

284,220,1210,1184

Explanation:

Basically the same idea python implementation: starts the variable N with the desired value, defines d as a Arrow Function calculating the sum of all divisors of n, after going through the entire list of N values down to a list of friends numbers. Used here [...Array(n).keys()] to generate a list of integers between 0 and n: [0, 1, 2, 3, ..., n-1].

See working on Repl.it.

16

Kotlin (151 bytes)

fun main(args: Array<String>){val n=1500;print((2..n).filter{i->d(d(i))==i&&i>d(i)}.map{"${it}-${d(it)}"})}fun d(n: Int)=(1..n-1).filter{n%it==0}.sum()

Readable version

fun main(args: Array<String>) {
    val n = 1500
    print((2..n)
          .filter{i -> d(d(i)) == i && i > d(i) }
          .map{"${ it }-${ d(it) }"})
}    

fun d(n: Int) = (1..n-1).filter { n % it == 0 }.sum()

See working on Try.Kotlin | Code on Github for future reference

Exit:

[284-220, 1210-1184]

The implementation is exactly the same as C# (and also Anderson’s answers).

15

C# (míseros 5.120 bytes)

Many Bytes! But what matters is that it’s working! hahaha

Code:

using System;class Program{static void Main(string[] args){int N = 1500; for (int n = 2; n < N; n++){double valor1 = somar(somar(n)); double valor2 = somar(n); if (n == valor1 && n != valor2)Console.WriteLine(valor1 + ", " + valor2);}}static double somar(double n, int sum = 0){for (int N = 1; N < n; N++)if ((n / N) % 1 == 0)sum += N; return sum;}}

Readable code:

using System;
class Program
{
    static void Main(string[] args)
    {
        int N = 1500;
        for (int n = 2; n < N; n++)
        {
            double valor1 = somar(somar(n)); double valor2 = somar(n);
            if (n == valor1 && n != valor2)
                Console.WriteLine(valor1 + ", " + valor2);
        }
    }
    static double somar(double n, int sum = 0)
    {
        for (int N = 1; N < n; N++)
            if ((n / N) % 1 == 0)
                sum += N; return sum;
    }
}

Exit:

220, 284
1184, 1210

5

Javascript (108 105 102 101 bytes)

N=1500,x={},r=[];for(i=1;N-++i;){s=0;for(j=i;--j;)x[i]=s+=i%j?0:j;x[s]==i&s!=i?r.push(i,s):0}alert(r)

This version uses a support dictionary to keep the numbers and their sums of divisors, and consequently check if there is Friend to the current number.

It is a solution a little more at hand, not using functions like reduce, map, filter, etc..

Legible version:

let N = 1500;
let numeros = {};
let res = [];

for(let i = 2;i <= N;++i){
    let soma = 0;
    for(let j = i - 1;j >= 1;--j) 
        soma += i % j!=0 ? 0:j;

    numeros[i] = soma;
    if(soma in numeros && numeros[soma] === i && soma !== i)
        res.push(i,soma);
}
alert(res);

  • I don’t understand why in the unreadable version i starts with 1, but readable with 2

  • I understand, the increment of the prefixed operator i is happening simultaneously with the comparison

Browser other questions tagged

You are not signed in. Login or sign up in order to post.