-
Notifications
You must be signed in to change notification settings - Fork 14
/
factorization.jl
77 lines (45 loc) · 1.58 KB
/
factorization.jl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# coding: utf-8
# In[1]:
#global list is the key
#otherwise we will lose the list throughout iterations
global factors=[]
# In[2]:
function factorization(num)
#negative and float should be excluded
if (num<0) || !(isinteger(num))
error("negative or float is not allowed")
end
#if n is smaller than 4
#prime number it is
if num>4
#exclude 1 and itself
#the largest factor of n can not exceed the half of n
#because 2 is the smallest factor
#the range of factors we are gonna try starts from 2 to fld(num,2)+1
#int function to solve the odd number problem
for i in 2:(fld(num,2)+1)
#the factorization process
if num%i==0
push!(factors,i)
#return is crucial
#if the number is not a prime number
#it will stop function from appending non-prime factors
#the next few lines will be ignored
return factorization(Int32(num/i))
end
end
end
#append the last factor
#it could be n itself if n is a prime number
#in that case there is only one element in the list
#or it could be the last indivisible factor of n which is also a prime number
push!(factors,num)
if length(factors)==1
println(num," is a prime number")
empty!(factors)
end
end
# In[3]:
factorization(71392643)
# In[4]:
print(factors)