skip to Main Content

I’m trying to write an AWK script that would check if there are any prime numbers in a file and print them. Here is my code:

#!/bin/awk -f

function is_prime(n) {
    if (n <= 1) return 0;
    if (n == 2) return 1;
    for (i = 2; i <= sqrt(n); i++) {
        if (n % i == 0) {
            return 0;
        }
    }
    return 1;
}

{
    gsub(/[^[:digit:]]/, " ");
    for (i = 1; i <= NF; i++) {
        if (is_prime($i)) {
            print $i;
        }
    }
}

i executed with a file containing the following text:

Math is179day foun193dary 
18
nachum17
19

It should print:

179
193
17
19

but it rather prints:

14
5
5

What is wrong with my code please?

edit: I would like to add that if replace the ‘print i’ line with ‘print $i’ then execute the script, no numbers are printed but only 3 blank lines.

2

Answers


  1. Your is_prime function code is alright, however problem is use of variable i inside the function and outside without letting function know that i is local. You can bypass this problem by declaring an additional argument in function signature and preserve original value of i outside.

    Read: How to make a variable local to a function

    You may use this awk script:

    function is_prime(n,  i) {
        if (n <= 1) return 0
        if (n == 2) return 1
        for (i = 2; i <= sqrt(n); i++) {
            if (n % i == 0) {
                return 0
            }
        }
        return 1
    }
    {
        gsub(/[^[:digit:]]+/, " ")
        for (i = 1; i <= NF; ++i) {
            if (is_prime($i)) {
                print $i
            }
        }
    }
    
    Login or Signup to reply.
  2. It seems the problem is related with reusing variable "i" in function is_prime and main. Try to rename it, in the function is_prime(), for example. In my case has resolved.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search