# confuse with awk user define function

I have solved Projecteuler Problem 3, but the thing is that I am not able to create the function in awk.

I have tried this working code (without function):

``````#!/usr/bin/awk -f
BEGIN{
n=600851475143;
x=2; # minimual prime
while ( x<n ) {
if ( (n%x) == 0 ) {
n = n/x
print n
} else { # if n not devisable then increment x+1
x++
}
}
}
``````

Not working with the function

``````#!/usr/bin/awk -f
# The prime factors of 13195 are 5, 7, 13 and 29.
# What is the largest prime factor of the number 600851475143 ?

function get.PrimeFactor(n) {
x=2; # minimual prime
while ( x<n ) {
if ( (n%x) == 0 ) {
n = n/x
print n
}

else { # if n not devisable then increment x+1
x++
}
}

BEGIN {

n = \$1 # input number by user
get.PrimeFactor(n)
}
``````

I have tried several ways to work with the function but no luck.

Can anyone highlight what I'm doing wrong?

-

Get rid of the dot. Valid awk function names consist of a sequence of letters, digits and underscore, and don't begin with digit.

-
hmm.. good to know... let me check with that.. thanks.. – Rahul Patil May 9 '13 at 6:30
now it is working.. but another issue why it not accepting `\$1` input value as command argument – Rahul Patil May 9 '13 at 6:43
I'm trying `awk -f script value` and it is not taking `value` as `\$1` – Rahul Patil May 9 '13 at 6:43
thanks tink, I did it using `ARGV[1]` – Rahul Patil May 9 '13 at 6:49
@tink, you forgot quotes around `\$1` and beware that with that syntax, `awk` expands ANSI C escape sequences (`\n`, `\b`...) in the argument provided. Using `ENVIRON` or `ARGV` doesn't have that problem. – Stéphane Chazelas May 9 '13 at 10:28

Working AWK Script with function.

``````#!/usr/bin/awk -f
# The prime factors of 13195 are 5, 7, 13 and 29.
# What is the largest prime factor of the number 600851475143 ?

function get_PrimeFactor(n) {
x=2; # minimual prime
while ( x<n ) {
if ( (n%x) == 0 ) {
n = n/x
}
else { # if n not devisable then increment x+1
x++
}
}
return n
}

BEGIN {

n = ARGV[1] # input number by user
print get_PrimeFactor(n)
}
``````
-