-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprimeFactorize.sh
More file actions
executable file
·65 lines (59 loc) · 1.13 KB
/
Copy pathprimeFactorize.sh
File metadata and controls
executable file
·65 lines (59 loc) · 1.13 KB
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
#!/bin/bash
# awlong2@illinois.edu 9/5/16
# Idea came from:
# https://github.com/spurdo-sparde/all/blob/master/coding-problems-solved/projects-solutions/pf.sh
# Examples of functions, loops, and recursion to find the prime factors of a number
# check if a number isPrime
# 0 = True
# 1 = False
isPrime()
{
local N=$1
# loop through numbers from 2 to sqrt(N)
local i
for ((i = 2; $((i*i)) <= $N; i++))
do
# if remainder(N/i) == 0, number is NOT prime
if [[ $((N%i)) == 0 ]]
then
return 1
fi
done
return 0
}
# $1=Number to check
# $2=Prime to start checking with
findPrimeFactor()
{
local N=$1
START=$2
# if $1 is prime, we're done!
if isPrime $N
then
printf "%d" $N
return
fi
# loop through numbers from $START to sqrt($1)
local p
for ((p = $START; $((p*p)) <= $N; p++))
do
# check if prime is a factor of the number
if isPrime $p
then
if [[ $((N%p)) == 0 ]]
then
N=$((N/p))
printf "%dx" $p
findPrimeFactor $N $p
return
fi
fi
done
}
# Actual script: loop over all command line arguments
for i in $@
do
printf "Prime Factors of %d:" $i
findPrimeFactor $i 2
printf "\n"
done