Count in factors: Difference between revisions

Content added Content deleted
m (→‎simple approach: added highlighting to the REXX section header.)
m (→‎{{header|Sidef}}: updated code)
Line 3,410: Line 3,410:
<lang ruby>class Counter {
<lang ruby>class Counter {
method factors(n, p=2) {
method factors(n, p=2) {
var out = [];
var a = gather {
while (n >= p*p) {
while (n >= p*p) {
while (n % p == 0) {
while (p `divides` n) {
out.append(p);
take(p)
n /= p;
n //= p
}
p = self.next_prime(p)
}
}
p = self.next_prime(p);
}
}
(n > 1 || out.len.is_zero) && out.append(n);
(n > 1 || a.is_empty) ? (a << n) : a
return out;
}
}
 

method is_prime(n) {
method is_prime(n) {
self.factors(n).len == 1
self.factors(n).len == 1
}
}
 

method next_prime(p) {
method next_prime(p) {
do {
do {
p == 2 ? (p = 3) : (p+=2)
p == 2 ? (p = 3) : (p+=2)
} while (!self.is_prime(p));
} while (!self.is_prime(p))
return p;
return p
}
}
}
}
 

for i in (1..100) {
100.times { |i|
say "#{i} = #{Counter().factors(i).join(' × ')}";
say "#{i} = #{Counter().factors(i).join(' × ')}"
}</lang>
}</lang>