ERROR: MethodError: no method matching &(::Int64, ::Vector{Int64})

1.3k views Asked by At

I'm writing a GCD program but I get this error message every time I try :

ERROR: MethodError: no method matching &(::Int64, ::Vector{Int64})
Closest candidates are:
  &(::Any, ::Any, ::Any, ::Any...) at C:\Users\Katia\AppData\Local\Programs\Julia-1.7.3\share\julia\base\operators.jl:655
  &(::T, ::T) where T<:Union{Int128, Int16, Int32, Int64, Int8, UInt128, UInt16, UInt32, UInt64, UInt8} at C:\Users\Katia\AppData\Local\Programs\Julia-1.7.3\share\julia\base\int.jl:336  &(::Integer, ::Missing) at C:\Users\Katia\AppData\Local\Programs\Julia-1.7.3\share\julia\base\missing.jl:170
  ...
Stacktrace:
 [1] findGCD(m::Int64, M::Int64)
   @ Main c:\Users\Katia\Documents\Sacha\Schlemblück\gcd test.jl:7
 [2] top-level scope
   @ REPL[2]:1

There is a type problem at line 7, but I don't see why. Here's the program :

function findGCD(m,M)
    a = []
    b = []
    for i in 2:trunc(Int64,√m)
        while mod(m|M,i) == 0
            if mod(m,i) == 0;  m÷i & push!(a,i) end <-- line 7
            if mod(M,i) == 0;  M÷i & push!(b,i) end
        end
    end
    prod(intersect(a,b))
end
1

There are 1 answers

2
Sundar R On

For the main question, the error occurs because & is not used for separating different statements under an if as you seem to have assumed. & is a "bitwise" operator i.e. used to operate on individual binary digits of a number. ; is the operator used to separate different subsequent statements, but just using a new line is usually better for readability.

if mod(m,i) == 0
  m = m÷i
  push!(a,i) 
end

There are several other issues with the code as pasted, both syntax issues and logical problems.

If your goal is just to find the GCD, use the inbuilt gcd function as @jling suggests. Otherwise, if you wish to create your own GCD function for the purpose of learning, I'd suggest starting small first, trying out the operators in the REPL and how they work in combination, and also working out your algorithm first by hand for a few examples before implementing it in code.