Lua : recursive multiple numbers GCD Euclide calculation -- everlasting loop - recursion

I try to calculate recusively the GCD of several numbers.
Here my try. with more than numbers two is an erverlasting loop.
I'm not sure about the pgcd( unpack(arg)) part, but I have no idea of something else.
Edit In fact, it seems to be the arg.n >2 that is not efficient...
function pgcd ( ... )
local arg = table.pack(...)
if arg.n >2
then
local tmp = table.remove(arg,1)
return pgcd (tmp, pgcd( unpack(arg) ))
else
a,b = unpack(arg)
repeat
a , b = b , a % b
until a % b == 0
return b
end
end
print (pgcd(18,12)) -- works fine
print (pgcd(18,12,9)) -- everlasting loop

In fact the endding test was testing once too far.
function pgcd ( ... )
local arg = table.pack(...)
if arg.n > 2
then
local tmp = table.remove(arg,1)
return pgcd (tmp, pgcd( unpack(arg) ) )
else
a,b = unpack(arg)
repeat
a , b = b , math.fmod(a,b)
until b == 0 -- test was once too far
return a
end
end
print (pgcd(18,12)) -- works fine
print (pgcd(18,12,6)) -- works fine

Related

Multiple outputs used repeatedly in for loop Julia

I am using Julia and I've designed a for loop that takes the outputs of a function in one loop and uses them as the input of that function in the next loop (and over and over). When I run this code, Julia flags an "undefined" error, however, if I run the code in debug mode, it executes perfectly. For example, the code looks like this:
function do_command(a,b,c,d)
a = a + 1
b = split(b, keepempty=false)[1]
c = split(b, keepempty=false)[1]
if a == 1000
d = true
else
d = false
end
return a, b, c, d
end
for ii in 1:length(x)
if ii == 1
a = 0
b = "string something"
c = ""
d = false
end
a,b,c,d = do_command(a,b,c,d)
if d == true
print(string(b))
break
end
end
What am I doing wrong here?
An issue with your code is that for introduces a new scope for each iteration of the loop. That is to say: variable a created within the loop body at iteration 1 is not the same as variable a created within the loop body at iteration 2.
In order to fix your problem, you should declare variables outside the loop, so that at each iteration, references to them from within the loop body would actually refer to the same variables from the enclosing scope.
I'd go with something like this:
function do_command(a,b,c,d)
a = a + 1
b = split(b, keepempty=false)[1]
c = split(b, keepempty=false)[1]
if a == 1000
d = true
else
d = false
end
return a, b, c, d
end
# Let's create a local scope: it's good practice to avoid global variables
let
# All these variables are declared in the scope introduced by `let`
a = 0
b = "string something"
c = ""
d = false
for ii in 1:10 #length(x)
# now these names refer to the variables declared in the enclosing scope
a,b,c,d = do_command(a,b,c,d)
if d == true
print(string(b))
break
end
end
end

Julia NLopt force stops before the first iteration

I'm using NLopt for a constrained maximization problem. Regardless of the algorithm or start values, the optimization program is force stopped even before the first iteration (or so I assume because it gives me the initial value). I've attached my code here. I'm trying to find probabilities attached to a grid such that a function is maximized under some constraints. Any help is appreciated.
uk = x -> x^0.5
function objective(u,p,grd)
-p'*u.(grd)
end
function c3(grd,p)
c =[]
d =[]
for i=1:length(grd)
push!(c,quadgk(x -> (i-x)*(x <= i ? 1 : 0),0,1)[1])
push!(d,sum(p[1:i]'*(grd[1:i] .- grd[i])))
end
return append!(d-c,-p)
end
function c4(grd,p)
return (grd .* p)-quadgk(x,0,1)
end
grd = n -> collect(0:1/n:1)
opt = Opt(:LD_SLSQP,11)
inequality_constraint!(opt, p -> c3(grd(10),p))
inequality_constraint!(opt, p -> -p)
equality_constraint!(opt, p -> sum(p)-1)
equality_constraint!(opt, p -> c4(grd(10),p))
opt.min_objective = p -> objective(-uk, p, grd(10))
k = push!(ones(11)*(1/11))
(minf,minx,ret) = optimize(opt, k)
I'm not a julia developer, but I only know this, if you need exit before complete the loop for is not your best choice, you need do a while with a sentinel variable.
here you have an article that explain you how while with sentinels works
and here you have a julia example changing your for to a while with a sentinel that exit after the third loop
i = 1
third = 0
while i < length(grd) && third != 1
# of course you need change this, it is only an example that will exit in the 3 loop
if i == 3
third = 1
end
push!(c,quadgk(x -> (i-x)*(x <= i ? 1 : 0),0,1)[1])
push!(d,sum(p[1:i]'*(grd[1:i] .- grd[i])))
i += 1
end

Subset sum using recursive backtracking in python using list and return statements.

I am trying to solve the subset sum problem using recursive back-tracking. While it works if I print the result instantly, it does not seem to work if I try to return it.
Here is a look at the code in python. I have added intermediate print statements to make things easier(please uncomment them):
l = [int(i) for i in input().split()]
num = int(input())
#print(num)
#print(l)
def subset(l):
tot = 0
ch = []
return(subsetHelper(l,tot,num,ch))
def subsetHelper(l,tot,num,ch):
#print("("+str(l)+" "+str(tot)+" "+str(num)+" "+str(ch)+")")
if(tot==num):
return(ch)
elif(tot>num or len(l)==0):
return
else:
ch.append(l[0])
return subsetHelper(l[1:],tot+l[0],num,ch)
del ch[-1]
return subsetHelper(l[1:],tot,num,ch)
print(subset(l))
The same concept works when I print the result without returning it.
l = [int(i) for i in input().split()]
num = int(input())
#print(num)
#print(l)
def subset(l):
tot = 0
ch = []
subsetHelper(l,tot,num,ch)
def subsetHelper(l,tot,num,ch):
#print("("+str(l)+" "+str(tot)+" "+str(num)+" "+str(ch)+")")
if(tot==num):
print(ch)
elif(tot>num or len(l)==0):
#return "Hello"
return
else:
ch.append(l[0])
subsetHelper(l[1:],tot+l[0],num,ch)
del ch[-1]
subsetHelper(l[1:],tot,num,ch)
subset(l)
Any suggestions?

Exception handling in a #testset in Julia

what is the prefered way to investigate or print out further detail (print input variable of a function, iteration number, etc.) of a failed #test inside a #testset?
I tried to wrap a try-catch-block around it. However, it doesn't seem to fire.
Here is a made-up example:
using Base.Test
rng = MersenneTwister(3231);
# define function that works different than expected
function compare(a,b)
if a == 3 && b == 3
return false
else
return a == b
end
end
# test function in a test set
#testset "Test Compare Function" begin
for iii = 1:10
number = rand(rng,1:10)
try
#test compare(number,number) == true
catch
#show(number)
end
end
end
Thank you very much!
You need to make sure it tests after the printing.
#testset "Test Compare Function" begin
for iii = 1:10
number = rand(rng,1:10)
#test begin
res = compare(number,number) == true
if !res
#show number
flush(STDOUT)
end
res
end
end
end

Printing variable subscripts in Julia

Hey so I know that due to the Unicode support in Julia one, may write for instance the letter a with the subscript 1 by typing a\_1<TAB>. Now, what if I wanted to do something like the following:
for i in [1 2 3]
println("a\_i")
end
and have the output be written as
a₁
a₂
a₃
How would I go about this without writing out all the possible subscripts myself?
You could do this (at least in version 0.6):
ltx = Base.REPLCompletions.latex_symbols
for i in 1:3
println("a$(ltx["\\_$i"])")
end
Bogumił Kamiński's answer seems the neatest, but I needed to reverse the order to get the correct string for two-digit numbers:
subscript(i::Integer) = i<0 ? error("$i is negative") : join('₀'+d for d in reverse(digits(i)))
for i=7:13 println("a"*subscript(i)) end
Building off the other answers here, I wrote a set of functions to allow for negative numbers and to work with the more complex superscript case.
function subscriptnumber(i::Int)
if i < 0
c = [Char(0x208B)]
else
c = []
end
for d in reverse(digits(abs(i)))
push!(c, Char(0x2080+d))
end
return join(c)
end
function superscriptnumber(i::Int)
if i < 0
c = [Char(0x207B)]
else
c = []
end
for d in reverse(digits(abs(i)))
if d == 0 push!(c, Char(0x2070)) end
if d == 1 push!(c, Char(0x00B9)) end
if d == 2 push!(c, Char(0x00B2)) end
if d == 3 push!(c, Char(0x00B3)) end
if d > 3 push!(c, Char(0x2070+d)) end
end
return join(c)
end
julia> for i in [1 -2 39]
println("a"*superscriptnumber(i))
println("a"*subscriptnumber(i))
end
a¹
a₁
a⁻²
a₋₂
a³⁹
a₃₉

Resources