Skip to content

Commit 5f7202a

Browse files
JohnnyPolkostis
andauthored
[Dana] Add factors and primeFactors programs (#58)
* Find prime Factors of a int and Find all non-trivial factors of an int Programs. --------- Co-authored-by: Kostis Sagonas <kostis@cs.ntua.gr>
1 parent 5d1132c commit 5f7202a

File tree

6 files changed

+67
-0
lines changed

6 files changed

+67
-0
lines changed

dana/programs/factors.dana

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
(*
2+
This program reads a positive integer from the user and prints all its factors.
3+
For the special cases where the number is 2 or 3, it directly prints the two factors: 1 and the number.
4+
*)
5+
6+
def main
7+
var n is int
8+
var i is int
9+
10+
# Read the input
11+
n := readInteger()
12+
13+
writeString: "Factors:"
14+
15+
# If n is 2 or 3, print the factors 1 and n, then exit
16+
if n = 2 or n = 3:
17+
writeString: " 1 "
18+
writeInteger: n
19+
exit
20+
21+
# For all other numbers, iterate from 1 to n and print divisors
22+
i := 2
23+
loop:
24+
if i > n / 2: break
25+
elif n % i = 0:
26+
writeString: " "
27+
writeInteger: i # i is a factor of n
28+
i := i + 1

dana/programs/factors.input

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
12

dana/programs/factors.result

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Factors: 2 3 4 6

dana/programs/primeFactors.dana

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
def main
2+
# Helper procedure: prints the prime factors of n
3+
def primeFactors: n as int
4+
# Divide out all factors of 2
5+
loop:
6+
if n % 2 = 0:
7+
writeString: " 2"
8+
n := n / 2
9+
else: break
10+
11+
var i is int
12+
i := 3
13+
# Loop over odd numbers starting from 3 while i*i <= n
14+
loop:
15+
if i * i <= n:
16+
loop:
17+
if n % i = 0:
18+
writeString: " "
19+
writeInteger: i
20+
n := n / i
21+
else: break
22+
i := i + 2
23+
else: break
24+
25+
# If remaining n is a prime greater than 2, print it
26+
if n > 2:
27+
writeString: " "
28+
writeInteger: n
29+
30+
# Main program: Read input and call primeFactors
31+
var num is int
32+
num := readInteger()
33+
writeString: "Prime factors:"
34+
primeFactors: num
35+
writeString: "\n"

dana/programs/primeFactors.input

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
153569623460

dana/programs/primeFactors.result

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Prime factors: 2 2 5 11 223 3130241

0 commit comments

Comments
 (0)