Home > Mobile >  Shell Function to Print factors of the first line argument
Shell Function to Print factors of the first line argument

Time:07-28

For a task I have to write a function that prints the number of numbers that are factors of 12 when provided with a sequence of numbers. My problem now is that my function keeps printing 0. What am I doing wrong?

Below is my code:

#!/usr/bin/bash
#File: Num_Factor
#Write a function which prints factors of the first argument

function num_factor {
  local sum=0
  for element in $@; do
    let factorcheck=$(( element % 2 ))
    if [[ $factorcheck -eq 0 ]]; then
      let sum=sum 1
    fi
  done
  echo $sum
}

num_factor

The expected output am trying to achieve should be something similar to this:

$num_factor 12 4 6 1 5
4

Thanks.

CodePudding user response:

Assumptions:

  • the first parameter is to be compared against itself
  • all parameters are guaranteed to be integers otherwise will need to use something else (bc? awk?)

Making a few tweaks to OP's current code:

num_factor() {
  local sum=0 first=$1                                    # initialize counter, grab first parameter
  # shift                                                 # uncomment this line if the first parameter is *NOT* to be compared with itself
  for element in "$@"; do
    [[ "$element"           -eq 0 ]] && continue          # skip 'divide by 0' scenario
    [[ $((first % element)) -eq 0 ]] && let sum=sum 1
  done
  echo $sum
}

Taking it for a test drive:

$ num_factor 12 4 6 1 5
4

$ num_factor 13
1

$ num_factor 13 2 3 5 7 9 11
1

$ num_factor -12 2 6 -3 5 1
5

$ num_factor 0 1 2 3 4 5 6
6                                   # based on OP's current logic; OP may want to reconsider how to address when 1st parameter == `0`

$ num_factor 720 2 3 4 5 6
6

CodePudding user response:

After updating my code..The issue seemed not to be fixed as shown below

  • Related