19
\$\begingroup\$

Write code that when given a positive number \$x\$ as input, outputs the largest positive divisor of \$x\$ less than or equal to the square root of \$x\$.

In other words find the largest \$n > 0\$ such that

\$\exists m\geq n:m\cdot n=x\$

(Exists \$m\$ greater than or equal to \$n\$ such that \$m\$ times \$n\$ is \$x\$)


For example if the input were \$12\$ the divisors are \$1\$, \$2\$, \$3\$, \$4\$, \$6\$, and \$12\$. \$1\$, \$2\$ and \$3\$ all multiply by larger numbers to get \$12\$, but \$3\$ is the largest so we return \$3\$.


This is so answers will be scored in bytes with fewer bytes being considered a better score.

Test Cases

(1,1)
(2,1)
(3,1)
(4,2)
(5,1)
(6,2)
(7,1)
(8,2)
(9,3)
(10,2)
(11,1)
(12,3)
(13,1)
(14,2)
(15,3)
(16,4)
(17,1)
(18,3)
(19,1)
(20,4)
(21,3)
(22,2)
(23,1)
(24,4)
(25,5)
(26,2)
(27,3)
(28,4)
(29,1)
(30,5)
(31,1)
(32,4)
(33,3)
(34,2)
(35,5)
(36,6)
(37,1)
(38,2)
(39,3)
(40,5)
(41,1)
(42,6)
(43,1)
(44,4)
(45,5)
(46,2)
(47,1)
(48,6)
(49,7)
(50,5)

OEIS A033676

\$\endgroup\$
  • 11
    \$\begingroup\$ I don't see how closing popular questions as dupes of older inactive ones help the site...? If you notice it early, sure, go ahead and hammer it. If it has twice the number of answers and more upvotes than the old one. Keep it, and if anything, close the other one... \$\endgroup\$ – Stewie Griffin Jun 21 '18 at 7:16
  • \$\begingroup\$ @StewieGriffin A problem with "popular questions" is that they're on HNQ. Which is probably not a very good thing. / I don't see how it harms the site either, you can just move the answers to the old one. \$\endgroup\$ – user202729 Jun 21 '18 at 8:02
  • 5
    \$\begingroup\$ The HNQ might attract new users, and that's a good thing (IMO). \$\endgroup\$ – Stewie Griffin Jun 21 '18 at 9:56
  • 1
    \$\begingroup\$ @qwr But the core idea is the same. The difference is very small. Method in each challenge can be used for another. \$\endgroup\$ – user202729 Jun 22 '18 at 0:47
  • 1
    \$\begingroup\$ @Hand-E-Food I don't claim this one is different. In fact I do believe that the two have the same content. My reasons for the closure of your question are the same as those in the comment at the top of the thread, this question has more answers. The meta is here if you would like to ask there. You may also have interest in this. \$\endgroup\$ – Post Rock Garf Hunter Jun 25 '18 at 23:18

34 Answers 34

10
\$\begingroup\$

Python3, 49 47 bytes

def f(x):
 l=x**.5//1
 while x%l:l-=1
 return l

Explanation

  • l=x**.5//1 → Assign l the largest integer less than equal to the square root of x
  • while x%l:l-=1 → While l does not evenly divide x, decrement l.

Edits

  • Mention Python3, not Python2
  • Use ...//1 to save two bytes. (Decimals are okay! Thanks @Rod)
\$\endgroup\$
  • \$\begingroup\$ Welcome to PPCG, nice first answer! You can save few bytes by using input/print instead def/return, you can also replace int(...) with ...//1 to save more bytes as you can see here \$\endgroup\$ – Rod Jun 20 '18 at 16:43
  • \$\begingroup\$ @Rod not //1, as I meant have said Python3. (Unless decimals are okay for the output, which I didn't think so.) But for Python2, thanks! \$\endgroup\$ – hunteke Jun 20 '18 at 17:04
  • \$\begingroup\$ @hunteke Decimal output is fine, I don't see any reason it ought not be. \$\endgroup\$ – Post Rock Garf Hunter Jun 20 '18 at 17:12
  • \$\begingroup\$ Would it be shorter with "For" instead of "While", so you can assign values in the conditional, possibly avoiding defining "l"? \$\endgroup\$ – Malady Jun 21 '18 at 3:30
8
\$\begingroup\$

MATL, 7 bytes

Z\tn2/)

Try it online!

For this explanation, we will use '12' as a sample input. Explanation:

Z\      % Divisors.
        % Stack:
        %   [1 2 3 4 6 12]
  t     % Duplicate.
        % Stack:
        %   [1 2 3 4 6 12]
        %   [1 2 3 4 6 12]
   n    % Number of elements.
        % Stack:
        %   6
        %   [1 2 3 4 6 12]
    2/  % Divide by 2
        % Stack:
        %   3
        %   [1 2 3 4 6 12]
      ) % Index (grab the 3rd element)
        % 3

This works because of a lot of lucky coincidences.

  1. MATL uses 1 indexing
  2. If we index with a non-integer (this will happen for any perfect square input), then <n>) will index \$\lceil n \rceil\$
\$\endgroup\$
  • 1
    \$\begingroup\$ ......well I've been soundly trounced! \$\endgroup\$ – Giuseppe Jun 20 '18 at 16:17
  • \$\begingroup\$ It had to be you who answered this in MATL :-) \$\endgroup\$ – Luis Mendo Jun 20 '18 at 21:56
  • \$\begingroup\$ BTW I think you can shorten to Z\J2/) (J2/ or equivalently .5j stands for end/2 when used as an index) \$\endgroup\$ – Luis Mendo Jun 20 '18 at 21:56
  • \$\begingroup\$ It might be worth explaining the behavior when applied to a number with an odd number of divisors, since "Index" with a non-integer value isn't obvious. \$\endgroup\$ – Kamil Drakari Jun 22 '18 at 15:45
  • \$\begingroup\$ @KamilDrakari How is that? \$\endgroup\$ – James Jun 22 '18 at 16:52
7
\$\begingroup\$

C (gcc) -lm, 35 bytes

i;f(n){for(i=sqrt(n);n%i;i--);n=i;}

Try it online!

\$\endgroup\$
  • 2
    \$\begingroup\$ BTW, this only works because of GCC's recognition of sqrt as a built-in function. With -fno-builtin-sqrt, gcc assumes int sqrt(int), and doesn't pass a double. On x86-64, double is passed in a different register than an integer. On 32-bit, a double would take 2 slots on the stack, so you'd also be passing garbage (or a subnormal with the integer as the bottom of the mantissa, if the upper 32bits were zero). This also breaks unless you're making a debug build because it relies on gcc's default un-optimized code-gen of evaluating expressions in the return-value register. \$\endgroup\$ – Peter Cordes Jun 21 '18 at 2:04
  • \$\begingroup\$ @PeterCordes Yes, it's code golf, not a medical device :-) \$\endgroup\$ – cleblanc Jun 21 '18 at 12:57
  • \$\begingroup\$ Well I'm not a fan of the fake-return hack. That's not even C anymore, it's just an implementation detail with one compiler setting which happens to be the default. (It's really stretching the "has to work with at least one implementation" rule.) The sqrt() issue is different: I was curious how that managed to work, because the caller has to somehow know to convert int to double. I posted the answer to that as a comment in case anyone else was curious. Effectively gcc has sqrt (including prototype) as a built-in, otherwise this would fail for reasons we sometimes see in SO asm Qs \$\endgroup\$ – Peter Cordes Jun 21 '18 at 13:02
  • \$\begingroup\$ i;f(n){for(i=0;++i<n/i||n%i;);} is 31B, and works with gcc -O on x86-64 (costing 2 or 3 more bytes for the command line option.) Using || instead of | causes gcc to leave the n/i result from idiv in EAX, the return-value register (godbolt.org/g/RJYeui). The undefined-behaviour from ++i without a sequence point happens to work. (The asm produced is basically the same as my x86 machine code answer.) With -O0, gcc always seems to leave i in EAX, but maybe we can use that... \$\endgroup\$ – Peter Cordes Jun 22 '18 at 23:58
  • \$\begingroup\$ Anyway, if you like non-C gcc implementation-details answers, maybe you'll like this x86-64 gcc answer that happens to work because of the asm produced by the compiler for clearly undefined behaviour: Try it online! (31+2 bytes) \$\endgroup\$ – Peter Cordes Jun 22 '18 at 23:59
5
\$\begingroup\$

05AB1E, 5 bytes

Ñ2äнθ

Try it online! or as a Test suite

Explanation

Ñ        # push the list of divisors
 2ä      # split it into 2 parts
   н     # take the first haft
    θ    # take the last element of that
\$\endgroup\$
5
\$\begingroup\$

APL (Dyalog Unicode), 16 14 12 bytes

I'm glad I was able to write some answer in APL since I only just learned it. Many, many thanks to Adám for help with golfing. Golfing suggestions very much welcome. Try it online!

To learn more about APL, take a look at The APL Orchard.

EDIT: -2 bytes to fixing a problem with my code. Thanks to H.PWiz for pointing out that problem. -2 bytes from shortening everything again.

⌈/{⍳⌊⍵*÷2}∨⊢

Ungolfing

⌈/{⍳⌊⍵*÷2}∨⊢
          ∨   GCD of the following...
           ⊢    The right argument, our input.
  {⍳⌊⍵*÷2}
     ⍵            Our input.
      *÷2         To the power of 1/2, i.e. square root.
    ⌊             Floor.
   ⍳              Indices up to floor(sqrt(input)).
                In total, range from 1 to floor(sqrt(input)).
⌈/            The maximum of the GCDs of our input with the above range.
\$\endgroup\$
  • \$\begingroup\$ Why do you strikethrough in reverse order? ... I often see ---16--- ---14--- 12, not 12 ---14--- ---16---. \$\endgroup\$ – user202729 Jun 22 '18 at 1:14
  • \$\begingroup\$ @user202729 Frankly, it's been a while, and I quite forgot the order of strikethrough. Will fix it shortly. \$\endgroup\$ – Sherlock9 Jun 22 '18 at 15:23
  • \$\begingroup\$ Actually it's not a problem, the leaderboard snippet supports both. \$\endgroup\$ – user202729 Jun 22 '18 at 16:05
4
\$\begingroup\$

Husk, 4 bytes

→←½Ḋ

Try it online!

Explanation

→←½Ḋ
   Ḋ      Divisors of (implicit) input.
  ½       Bisect.
→←        Take the last element of the first half.
\$\endgroup\$
3
\$\begingroup\$

R, 45 33 bytes

function(x,y=1:x^.5)max(y[!x%%y])

Try it online!

Original:

function(x,y=x/1:x^.5)max(which(y==floor(y)))

Try it online!

\$\endgroup\$
3
\$\begingroup\$

x86 32-bit (IA32) machine code: 18 16 bytes

changelog: handle the n=1 test case correctly, save 2 bytes, and return in EAX.

Count up until n/i <= i (i.e. when we reach the sqrt), and use the first exact divisor after that.

A 64-bit version of this is callable from C with the x86-64 System V calling convention, as
int squarish_root_countup(int edi).

nasm -felf32 -l/dev/stdout squarish-root.asm:

58                         DEF(squarish_root_countup)
59                             ; input: n in EDI
60                             ; output: EAX
61                             ; clobbers: eax,ecx,edx
62                         .start:
63 00000025 31C9               xor    ecx, ecx
64                         .loop:                    ; do{
65                         
66 00000027 41                 inc    ecx                ; ++i
67 00000028 89F8               mov    eax, edi
68 0000002A 99                 cdq
69 0000002B F7F9               idiv   ecx                ; edx=n%i    eax=n/i
70                         
71 0000002D 39C1               cmp    ecx, eax
72 0000002F 7CF6               jl     .loop          ; }while(i < n/i
73                                                   ;          || n%i != 0);  // checked below
74                             ; falls through for i >= sqrt(n)
75                             ; so quotient <= sqrt(n) if we get here
76                         
77                                                   ; test edx,edx / jnz  .loop
78 00000031 4A                 dec    edx            ; edx-1 is negative only if edx was zero to start with
79 00000032 7DF3               jge   .loop           ; }while(n%i >= 1);
80                             ; falls through for exact divisors
81                         
82                             ; return value = quotient in EAX
83                         
84 00000034 C3                 ret

           0x10 bytes = 16 bytes.

85 00000035 10             .size: db $ - .start

Try it online! with an asm caller that uses the first byte of argv[1] as an integer directly, and uses the result as process exit status.

$ asm-link -m32 -Gd squarish-root.asm && 
for i in {0..2}{{0..9},{a..f}};do 
    printf "%d   " "0x$i"; ./squarish-root "$(printf '%b' '\x'$i)"; echo $?;
done

0   0  # bash: warning: command substitution: ignored null byte in input
1   1
2   1
3   1
4   2
5   1
6   2
7   1
8   2
9   3
10   0       # this is a testing glitch: bash ate the newline so we got an empty string.  Actual result is 2 for n=10
11   1
12   3
13   1
14   2
15   3
16   4
   ...
\$\endgroup\$
  • 1
    \$\begingroup\$ Are you sure n=1 isn't just 1? It is listed as a test case and it is a divisor ≤ √1 = 1. \$\endgroup\$ – qwr Jun 21 '18 at 4:35
  • \$\begingroup\$ Your answer should work for 1. If it doesn't work with your algorithm then you are going to have to hard code it. \$\endgroup\$ – Post Rock Garf Hunter Jun 21 '18 at 5:55
  • 2
    \$\begingroup\$ @qwr: updated with a shorter version that works for all inputs. \$\endgroup\$ – Peter Cordes Jun 21 '18 at 21:12
2
\$\begingroup\$

Japt -h, 8 6 bytes

â f§U¬

Try it

2 bytes saved thanks to Oliver


Explanation

           :Implicit input of integer U
â          :Divisors of U
  f        :Filter
   §       :  Less than or equal to
    U¬     :  Square root of U
           :Implicitly get the last element in the array and output it
\$\endgroup\$
  • \$\begingroup\$ Don't flags still cost bytes? \$\endgroup\$ – mbomb007 Jun 20 '18 at 15:19
  • \$\begingroup\$ @mbomb007 No. Each instance of a flag is considered a new language entry. \$\endgroup\$ – Oliver Jun 20 '18 at 15:21
  • \$\begingroup\$ Never mind. I guess I hadn't seen that meta post yet. \$\endgroup\$ – mbomb007 Jun 20 '18 at 15:21
2
\$\begingroup\$

Jelly, 5 bytes

ọⱮ½TṪ

Try it online!

\$\endgroup\$
2
\$\begingroup\$

JavaScript ES7, 33 31 bytes

n=>(g=x=>n%x?g(x-1):x)(n**.5|0)

Try it online

\$\endgroup\$
2
\$\begingroup\$

Snowman, 38 bytes

((}1vn2nD`#nPnF|:|NdE|;:,#NMo*|,;bW*))

Try it online!

((
  }        activate variables b, e, and g
  1vn2nD`  e=1/2
  #        retrieve the input into b
  nP       set b=b^e, which is sqrt(input)
  nF       floor the square root
  |        move b into g so there's space for a while loop
  :        body of the loop
    |NdE|  decrement the value in g
  ;:       loop condition
    ,#     assign b=input, e=current value
    NMo    store the modulo in g
    *|     discard the input value and place the modulo in the condition slot
    ,      put the current value back into g
  ;bW      continue looping while the modulo is nonzero
  *        return the result
))
\$\endgroup\$
2
\$\begingroup\$

dc, 24

?dsnv1+[1-dlnr%0<m]dsmxp

Try it online!

Explanation:

?                         # read input
 d                        # duplicate
  sn                      # store copy 1 in register n
    v                     # take the square root of copy 2
     1+                   # add 1
       [          ]       # define macro to:
        1-                #   subtract 1
          d               #   duplicate
           ln             #   load from register n
             r            #   reverse top 2 stack members
              %           #   calculate modulo
               0<m        #   if not 0, recursively call macro m again
                   d      # duplicate macro
                    sm    # store copy 1 in register m
                      x   # execute copy 2
                       p  # print final value
\$\endgroup\$
2
\$\begingroup\$

J, 24 19 bytes

-5 bytes thanks to Sherlock's GCD idea

([:>./+.)1+i.@<.@%:

Try it online!

original answer

([:{:]#~0=]|[)1+i.@<.@%:

Try it online!

parsed

┌───────────────────────────────┬──────────────────────┐
│┌──┬──┬───────────────────────┐│┌─┬─┬────────────────┐│
││[:│{:│┌─┬─────┬─────────────┐│││1│+│┌─────────┬─┬──┐││
││  │  ││]│┌─┬─┐│┌─┬─┬───────┐││││ │ ││┌──┬─┬──┐│@│%:│││
││  │  ││ ││#│~│││0│=│┌─┬─┬─┐│││││ │ │││i.│@│<.││ │  │││
││  │  ││ │└─┴─┘││ │ ││]│|│[││││││ │ ││└──┴─┴──┘│ │  │││
││  │  ││ │     ││ │ │└─┴─┴─┘│││││ │ │└─────────┴─┴──┘││
││  │  ││ │     │└─┴─┴───────┘│││└─┴─┴────────────────┘│
││  │  │└─┴─────┴─────────────┘││                      │
│└──┴──┴───────────────────────┘│                      │
└───────────────────────────────┴──────────────────────┘

explanation

  • 1 + i.@<.@%: gives the range 1 .. floor(sqrt).
  • the entire verb (A) B forms a hook, with the above range passed as the right arg ] to A and the original number passed as its left arg [. Thus...
  • ] | [ gives the remainer of each item in the range divided into the original arg.
  • and 0 = ] | [ gives the divisors with no remainder.
  • ] #~ ... then filters the range, leaving only those.
  • and {: gives the last item in the list, ie, the largest one.
\$\endgroup\$
1
\$\begingroup\$

Jelly, 5 bytes

½ḍƇµṪ

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Haskell, 36 bytes

f x=[z|y<-[1..],z<-[1..y],y*z==x]!!0

Try it online!

Well this is my answer to this challenge. This uses a particular list comprehension to find the answer. In our list comprehension we pick \$y\$ from the infinite list [1..] that is the positive integers, and we pick \$z\$ from the list [1..y]. This means that \$(y,z)\$ is all the ordered pairs such that \$y \geq z\$.

We then select only those pairs such that \$y\cdot z=x\$, meaning that we make the list of all pairs of numbers that multiply to \$x\$. Now since our comprehension is based first on \$y\$ and then \$z\$ this means that our pairs are in ascending order of \$y\$, or more usefully in descending order of \$z\$.

So to get the largest \$z\$ we take the \$z\$ belonging to the first element. This is our result.

\$\endgroup\$
1
\$\begingroup\$

QBasic (4.5), 52 bytes

INPUT x
FOR i=1TO sqr(x)
if x/i=x\i then m=i
next
?m
\$\endgroup\$
1
\$\begingroup\$

Forth (gforth), 53 bytes

The shortest way seems to be using the floating point stack and fsqrt, the shortest I could get without it was 62 bytes using /mod and checking if the quotient was greater than the divisor.

: f dup s>f fsqrt f>s 1+ begin 1- 2dup mod 0= until ;

Try it online!

Explanation

  1. Calculate the square root
  2. Starting at the square root, decrement by 1 until we find a factor of the original number

Code Explanation

: f                \ Start a word definition
dup                \ duplicate the input
s>f fsqrt          \ move the number to the float stack and get the square root
f>s                \ truncate result and move to integer stack
1+                 \ add 1 to the square root
begin              \ start indefinite loop
  1- 2dup          \ decrement divisor and duplicate input and divisor
  mod              \ calculate n % divisor
0= until           \ if result equals 0 (no remainder) end the loop
;                  \ end the word definition
\$\endgroup\$
1
\$\begingroup\$

F#, 55 49 bytes

let f x=Seq.findBack(fun i->x%i=0.0){1.0..x**0.5}

Try it online!

Seq.findBack: Returns the last element for which the given function returns True. The function in this case checks to see if a number is a factor of the value.

\$\endgroup\$
1
\$\begingroup\$

Brain-Flak, 144 bytes

{({}{}<<>({}<>)<>([({})()]<>({}(<>)())){(<{}({}[()]{}<({}())>)>)}{}((({}<>)<>(({})))[({}[{}])])>[({<({}[()])><>({})<>}{}<><{}>)])}{}{}<>{}({}<>)

Try it online!

I'm not really sure this answer is very good. I feel like there may be a nice way to solve this task however I'm just not clever enough.

Explanation

I tried to do an exploded view of the answer but there are so many moving parts it was not very enlightening, so here is an explanation of what the code does.

The first important bit is this

({}<>)<>([({})()]<>({}(<>)())){(<{}({}[()]{}<({}())>)>)}{}

This takes the two numbers on top of the stack and if they are unequal increments the second one, if they are equal it increments the first one and replaces the second one with zero. If we repeat this code a bunch we will get all the pairs \$(x,y)\$ such that \$x \geq y\$.

The next part is multiplication, taken with modification from the wiki. This multiplication is special because it preserves the existing values without destroying them. It goes like:

((({}<>)<>(({})))[({}[{}])])({<({}[()])><>({})<>}{}<><{}>)

So we are multiplying all these ordered pairs. For each result we check if it is equal to the input. If so we terminate and return the smaller item in the pair.

\$\endgroup\$
1
\$\begingroup\$

Python 2, 41 bytes

n=k=input()
while(k*k>n)+n%k:k-=1
print k

Try it online!

\$\endgroup\$
0
\$\begingroup\$

Jelly, 6 bytes

ÆDŒHḢṪ

Try it online!

\$\endgroup\$
0
\$\begingroup\$

Perl 5 -p, 26 bytes

$\=0|sqrt;$\--while$_%$\}{

Try it online!

\$\endgroup\$
0
\$\begingroup\$

Rust, 71 70 bytes

fn f(x:u64)->u64{let mut l=(x as f64).sqrt()as u64;while x%l>0{l-=1}l}

Pre-uglified version

fn f(x: u64) -> u64 {                    // function takes u64, gives u64
  let mut l = (x as f64).sqrt() as u64;  // l takes integer'ed root value
  while x % l > 0 {                      // loop while l leaves remainder
    l -= 1                               // decrement
  }
  l                                      // return the found value
}

Edits

  • Save a byte with > 0 over != 0. (Thanks to @CatWizard)
\$\endgroup\$
  • \$\begingroup\$ Can != be replaced with >? \$\endgroup\$ – Post Rock Garf Hunter Jun 20 '18 at 17:46
  • \$\begingroup\$ Good call! Yes. \$\endgroup\$ – hunteke Jun 20 '18 at 17:46
0
\$\begingroup\$

Japt, 8 bytes

â w æ§Uq

Try it online!

\$\endgroup\$
0
\$\begingroup\$

Triangularity, 49 bytes

....)....
...@_)...
..IEdF)..
.2)1/)IE.
^>{m.....

Try it online!

\$\endgroup\$
0
\$\begingroup\$

Pyret, 93 bytes

{(z):rec f={(i,x):if num-modulo(i, x) == 0:x else:f(i,x - 1)end}
f(z,num-floor(num-sqrt(z)))}

You can try this online by copying it into the online Pyret editor!

The above evaluates to an anonymous function. When it is applied to an integer, it returns a result according to the specification.

\$\endgroup\$
0
\$\begingroup\$

Actually, 7 bytes

Based on my APL answer here. Golfing suggestions welcome! Try it online!

;√LR♀gM

Ungolfing

;√LR♀gM  Implicit input n
;        Duplicate n
 √       sqrt(n)
  L      floor(sqrt(n))
   R     1..floor(sqrt(n))
    ♀g   gcd(n, foreach(1..floor(sqrt(n)))
      M  The maximum of the GCDs.
         Return this maximum.
\$\endgroup\$
0
\$\begingroup\$

A port of this Mathematica answer.

Jelly, 11 bytes

½ðḞ³÷Ċ³÷µÐL

Try it online!

This (11 bytes) also works, and don't depend on ³:

½Ḟ÷@Ċ÷@ʋƬµṪ

Unfortunately ½Ḟ÷@Ċ÷@ʋÐL (10 bytes) doesn't work. And apparently Ƭ and ÐĿ is not exactly the same (when the link is dyadic)


Method: (let \$n\$ be the input)

  • Start with an upper bound \$i = \sqrt n\$ of the answer \$a\$.
  • At each step:
    • If \$i\$ is not an integer, then the upper bound can be made \$\lfloor i\rfloor\$ (because the result must be an integer)
    • If \$n\over i\$ is not an integer, then \$a \le i \Rightarrow \frac n a \ge \frac n i \Rightarrow \frac n a \ge \lceil \frac n i \rceil \Rightarrow a \le n \div \lceil \frac n i \rceil \$.
  • So we repeatedly replace \$i\$ with \$n \div \lceil \frac n {\lfloor i\rfloor} \rceil\$ until it's fixed.
\$\endgroup\$
0
\$\begingroup\$

Java 8, 65 54 bytes

n->{int r=(int)Math.sqrt(n);for(;n%r>0;r--);return r;}

Port of @hunteke's Python 3 answer.

Try it online.


Old 65 bytes answer:

n->{int r=1,i=n;for(;i-->1;)r=n%i<1&n/i<=i&n/i>r?n/i:r;return r;}

Try it online.

Explanation:

n->{                // Method with integer as both parameter and return-type
  int r=1,          //  Result-integer, starting at 1
  i=n;for(;i-->1;)  //  Loop `i` in the range (n, 1]
    r=n%i<1         //   If `n` is divisible by `i`,
      &n/i<=i       //   and if `n` divided by `i` is smaller than or equal to `i` itself,
      &n/i>r?       //   and if `n` divided by `i` is larger than the current `r`
       n/i          //    Set `n` divided by `i` as the new result `r`
      :             //   Else:
       r;           //    Leave result `r` unchanged
  return r;}        //  Return the result `r`
\$\endgroup\$

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.