Factors and Other Properties

A simple program to determine factors and other properties of a given number.

First up, read the number from the user. Then, using an iterative for loop, determine the factors of the number and add them to an array. This is a brute force search, so by only searching up to number/2, the program’s run time is cut in half (since there are no factors above this limit).

Next, print the properties of the number:

  1. Print the factors to the screen by running through the factors array one at a time.
  2. Calculate and display the sum of the factors.
  3. Check the number of factors to determine if the number is prime.
  4. Check the sum of the factors to determine if the number is perfect.
#!/bin/bash
#set -xv

read -p "Enter number to determine factors of: " number

factors=()
sum=0

for (( i=1; i<=$(($number/2)); i++ ))
do
     if (( $number % $i == 0 ))
     then
          factors+=($i)
     fi
done

factors+=($number)

echo "Factors of $number are:"

for (( j=0; j<${#factors[@]}; j++ ))
do
     (( ${#factors[@]} - 1 == $j )) && { echo -n "and ${factors[$j]}."; break; }
     echo -n "${factors[$j]}, "
done

for (( k=0; k<${#factors[@]}; k++ ))
do
     sum=$(( ${factors[k]} + $sum ))
done

echo -e "\nSum of these factors is: $sum"

(( ${#factors[@]} == 2 )) && { echo "This is a prime number!"; }

(( $(( $sum / 2 == $number )) )) && { echo "This is a perfect number!"; }

Sample output:

Enter number to determine factors of: 360
Factors of 360 are:
1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 18, 20, 24, 30, 36, 40, 45, 60, 72, 90, 120, 180, and 360.
Sum of these factors is: 1170
Enter number to determine factors of: 6451
Factors of 6451 are:
1, and 6451.
Sum of these factors is: 6452
This is a prime number!
Enter number to determine factors of: 8128
Factors of 8128 are:
1, 2, 4, 8, 16, 32, 64, 127, 254, 508, 1016, 2032, 4064, and 8128.
Sum of these factors is: 16256
This is a perfect number!

 

Tagged , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published.

Protected by WP Anti Spam