-6

I want to divide number without divide operator

def divede_me(val,ded)
    i = 1; new_num=0
    rem = val % ded
    val = val - rem
    while (val != new_num)
        i += 1      
        new_num = ded * i       
    end 
    return i
end

p divede_me(14,4)

above script return 3 but i want floating point also (for Ex. 3.5) and best way to write above script.

dr. strange
  • 665
  • 7
  • 22
  • 1
    why you need this ? – Thorin Jun 01 '16 at 10:52
  • to improve script writing skill in ruby. – dr. strange Jun 01 '16 at 11:02
  • 5
    `val./(ded.to_f)` doesn't use a Ruby operator in the syntax sense. `Math.exp( Math.log(val) - Math.log(ded) )` doesn't do division directly, but it doesn't implement division logic as performed by fp processor. I don't see how either of these improve script writing either. The problem is more a computer science or maths thing. Could you be clearer on the goal of what you mean by "operator", and what kind of solutions you have been told are allowed? Without a clear goal, the "best" way to write that script is *to not write the script* . . . especially if "best" means most efficient – Neil Slater Jun 01 '16 at 11:07
  • I added a solution, but I have to agree with @NeilSlater this is a computer science or math than enhance script writing. – pshoukry Jun 01 '16 at 11:43

2 Answers2

1
def divide_me(val,ded)
    i = 1; new_num=0
    rem = val.to_f % ded
    val = val - rem
    while (val != new_num)
        i += 1
        new_num = ded * i
    end
    temp = 0.01
    temp += 0.01 until ded * temp >= rem
    return i + temp.round(2)
end

p divide_me(14,4)
=>3.5
p divide_me(15,4)
=>3.75
p divide_me(16,7)
=>2.29

Expanding on your existing code, this will get you to reasonably accurate 2 decimal places. Remove the .round(2) to see how inaccurate floats are.

Ropeney
  • 1,065
  • 8
  • 10
0

This logic may help you

val = 14
ded = 4

r = val % ded
value = val -r

v_ck = 0
i = 0
while( value != v_ck ) 

    i+=1
    v_ck =  ded * i
end

ded_ck = 0
j = 0
while(ded_ck != ded)    
   j += 1 
   ded_ck = r * j
end

puts  i.to_s+"."+j.to_s
Mukesh
  • 921
  • 10
  • 23