Count in factors: Difference between revisions

+Java
(→‎{{header|Visual Basic .NET}}: Added implementation)
(+Java)
Line 135:
10: 2 5
11: 11</lang>
=={{header|Java}}==
 
{{trans|Visual Basic .NET}}
<lang java>public class CountingInFactors{
public static void main(String[] args){
for(int i = 1; i<= 10; i++){
System.out.println(i + " = "+ countInFactors(i));
}
for(int i = 9991; i <= 10000; i++){
System.out.println(i + " = "+ countInFactors(i));
}
}
private static String countInFactors(int n){
if(n == 1) return "1";
StringBuilder sb = new StringBuilder();
n = checkFactor(2, n, sb);
if(n == 1) return sb.toString();
n = checkFactor(3, n, sb);
if(n == 1) return sb.toString();
for(int i = 5; i <= n; i+= 2){
if(i % 3 == 0)continue;
n = checkFactor(i, n, sb);
if(n == 1)break;
}
return sb.toString();
}
private static int checkFactor(int mult, int n, StringBuilder sb){
while(n % mult == 0 ){
if(sb.length() > 0) sb.append(" x ");
sb.append(mult);
n /= mult;
}
return n;
}
}</lang>
Output:
<pre>1 = 1
2 = 2
3 = 3
4 = 2 x 2
5 = 5
6 = 2 x 3
7 = 7
8 = 2 x 2 x 2
9 = 3 x 3
10 = 2 x 5
9991 = 97 x 103
9992 = 2 x 2 x 2 x 1249
9993 = 3 x 3331
9994 = 2 x 19 x 263
9995 = 5 x 1999
9996 = 2 x 2 x 3 x 7 x 7 x 17
9997 = 13 x 769
9998 = 2 x 4999
9999 = 3 x 3 x 11 x 101
10000 = 2 x 2 x 2 x 2 x 5 x 5 x 5 x 5</pre>
=={{header|Perl 6}}==
<lang perl6># Define a lazy list of primes.
Anonymous user