21
\$\begingroup\$

Your function takes a natural number and returns the smallest natural number that has exactly that amount of divisors, including itself.

Examples:

f(1) =  1 [1]
f(2) =  2 [1, 2]
f(3) =  4 [1, 2, 4]
f(4) =  6 [1, 2, 3, 6]
f(5) = 16 [1, 2, 4, 8, 16]
f(6) = 12 [1, 2, 3, 4, 6, 12]
 ...

The function doesn't have to return the list of divisors, they are only here for the examples.

\$\endgroup\$
3
  • 2
    \$\begingroup\$ Is this code-golf or code-challenge? \$\endgroup\$
    – marinus
    Apr 3 '13 at 12:49
  • \$\begingroup\$ Oops, forgot about that tag, code-golf! \$\endgroup\$
    – SteeveDroz
    Apr 3 '13 at 13:06
  • 12
    \$\begingroup\$ A005179 \$\endgroup\$ Apr 3 '13 at 15:28

32 Answers 32

1
2
0
\$\begingroup\$

C, 59 bytes

i,n,d;f(x){for(n=i=x;n;++i)for(n=x,d=i;d;n-=!(i%d--));--i;}

Works when compiled in Debug mode in Visual Studio.

A readable version:

int i, n, d;
f(x)
{
    i = x; // start searching from x; could also start from 0
    do {
        n = x; // n counts downward; if it hits 0, found then number
        for (d = i; d != 0; d--) // check all divisors
            n -= (i % d == 0); // subtract 1 if divisible
        ++i;
    } while (n != 0);
    return i - 1; // compensate for 1 extra iteration
}
\$\endgroup\$
0
\$\begingroup\$

Ruby 2.7, 58 56 bytes

Fairly straightforward, checks number of divisors for every number up to 2^n

->n{(1..2**n).find{|a|(1..a).select{|b|a%b==0}.size==n}}
\$\endgroup\$
1
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.