Find factors of a number (factorization)

Linux has got a beautiful factor finding tool called factor. This script does the same job of factor tool.

In mathematicsfactorization (also factorisation in British English) or factoring is the decomposition of an object (for example, a number, a polynomial, or a mtrix) into a product of other objects, or factors, which when multiplied together give the original. For example, the number 15 factors into primes as 3 × 5, and the polynomial x2 − 4 factors as (x − 2)(x+ 2). In all cases, a product of simpler objects is obtained.
                                                                   -Wikipediahttp://en.wikipedia.org/wiki/Factorization )


-------------------------------------------------------------------------------------------------------------------------------------------------
HOW THIS SCRIPT WORKS:
The number provided is divided by natural numbers starting from 2. Each natural number recursively divides the number while reminder for each division operation is zero.If reminder is not zero , the script starts dividing with the next natural number.
-------------------------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------

#!/bin/bash

#to find factors of a number
num=$1
for (( i=2; i<=$1; i++ ));do
    while [ $((num%$i)) == 0 ];do
        echo $i
        num=$((num/$i))
    done
done


-------------------------------------------------------------------------------------------


Script is called myfactor in my system. Figure shows finding factors with factor tool and then with myfactor script of 15, 40 and 13



.. are the results same ?? :)

Enjoy Linux !!

Don't know what to do with these codes ??  click here

No comments:

Post a Comment