# Help me: function in Julia

Hi, so I actually want to write a code that would show me the result of factorial of:
x = x + 2
y = x*(x-1) * y
but when I tried to put it in function, it doesn’t behave the way I want to. It needs to define the x and y outside the function, but when I did it like this:

x=1
y=0

function fact(x,y)

``````fact(n::Int) = n == 0 ? 1 : n*fact(n-1)
while x!=n
x = x + 2
y = x*(x-1) * y
end
``````

end
@show x y

the result of x and y are 1 and 0. The function doesn’t want to calculate the formula given.
Where did I do wrong? Thank you

You are trying to manipulate global variables, which is generally bad, and extra bad for performance in Julia. If that’s really what you want to do, then you need to mark them as global within your function.

1 Like

I don’t understand what you’re trying to do, but one thing that’s clear is that you didn’t call your function, but expect it to execute. It won’t unless you call it.

1 Like

You also have this

inside your other `fact` definition, which just sits there doing nothing. What is it for?

so I’m trying to do this equation (in a function):

increase x while maintaining invariant:
x=x+2
y=x*(x-1)*y

now I try to call the function by using this:

x=0
y=1
n=6
function fact(x,y)

``````while x!=n
p = x + 2
q = x*(x-1) * y
end
``````

end

(p,q)=fact(x,y)
@show x y

but I have been execute this for more than 5 minutes but no result come out yet. I’m using VS code anyway.

Thank you

There are many things that need improvement in your function, but the first thing is: The input value of `x` is 0, and `n` is 6. And since your function never updates `x`, it will never equal `n` and keeps looping forever.

Also, your function doesn’t return anything, so writing

won’t work.

thank you. now it works!

x=0
y=1
n=6
function fact(x,y)

``````while x!=n
x = x + 2
y = x*(x-1) * y
end
return x,y
``````

end

(x,y)=fact(x,y)
@show x y

Your function still access global variable `n`. It would be better to make it a parameter, too.

thank you! changed it to:

function fact(n)
x=0
y=1
while x!=n
x = x + 2
y = x*(x-1) * y
end
x,y
end
(x,y)=fact(6)
@show x y