Factors of an integer: Difference between revisions

From Rosetta Code
Content added Content deleted
mNo edit summary
(add Tcl)
Line 39: Line 39:
end
end
p 45.factors</lang>
p 45.factors</lang>

=={{header|Tcl}}==
<lang tcl>proc factors {n} {
set factors {1}
for {set i 2} {$i <= sqrt($n)} {incr i} {
if {$n % $i == 0} {
lappend factors $i [expr {$n / $i}]
}
}
return [lsort -unique -integer $factors]
}
puts [factors 64]
puts [factors 45]
puts [factors 53]</lang>
output
<pre>1 2 4 8 16 32
1 3 5 9 15
1</pre>

Revision as of 17:08, 15 August 2009

Task
Factors of an integer
You are encouraged to solve this task according to the task description, using any language you may know.

Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.

You may see other such operations in the Basic Data Operations category, or:

Integer Operations
Arithmetic | Comparison

Boolean Operations
Bitwise | Logical

String Operations
Concatenation | Interpolation | Comparison | Matching

Memory Operations
Pointers & references | Addresses

Compute the factors of a number.

See also Prime decomposition

Clojure

<lang lisp>(defn factors [n] (filter #(zero? (rem n %)) (range 1 n)))

(print (factors 45))</lang>

(1 3 5 9 15)

Python

<lang python>>>> def factors(n): return [i for i in range(1,n//2) if not n%i]

>>> factors(45) [1, 3, 5, 9, 15]</lang>

Ruby

<lang ruby>class Integer

 def factors() (1..self - 1).select { |n| (self % n).zero? } end

end p 45.factors</lang>

[1, 3, 5, 9, 15]

As we only have to loop up to , we can write <lang ruby>class Integer

 def factors()
   2.upto(Math.sqrt(self)).select {|i| (self % i).zero?} \
                          .inject([1]) {|f, i| f << i << self/i} \
                          .sort
 end

end p 45.factors</lang>

Tcl

<lang tcl>proc factors {n} {

   set factors {1}
   for {set i 2} {$i <= sqrt($n)} {incr i} {
       if {$n % $i == 0} {
           lappend factors $i [expr {$n / $i}]
       }
   }
   return [lsort -unique -integer $factors]

} puts [factors 64] puts [factors 45] puts [factors 53]</lang> output

1 2 4 8 16 32
1 3 5 9 15
1