このプログラムは素因数を見つけて、次のように出力します: factor (order) factor (order)
import java.util.Scanner;
import java.util.ArrayList;
public class Factorise2
{
public static ArrayList<Integer> get_prime_factors(int number)
{
//Get the absolute value so that the algorithm works for negative numbers
int absoluteNumber = Math.abs(number);
ArrayList<Integer> primefactors = new ArrayList<Integer>();
ArrayList<Integer> newprimes = new ArrayList<Integer>();
int b;
int c = (int)Math.sqrt(absoluteNumber);
//Get the square root so that we can break earlier if it's prime
for (int j = 2; j <= absoluteNumber;)
{
//Test for divisibility by j, and add to the list of prime factors if it's divisible.
if (absoluteNumber % j == 0)
{
primefactors.add(j);
absoluteNumber /= j;
c = (int)Math.sqrt(absoluteNumber);
}
else
{
for (int a = 0; a < newprimes.size();)
{
//Change j to the next prime
b = newprimes.get(a);
if (j % b == 0)
{
j++;
a = 0;
}
else
{
a++;
}
}
newprimes.add(j);
}
if (j > c)
{
primefactors.add(absoluteNumber);
break;
}
}
return primefactors;
}
public static void main(String[] args)
{
//Declare and initialise variables
int number;
int count = 1;
Scanner scan = new Scanner(System.in);
//Get a number to work with
System.out.println("Enter integer to analyse:");
number = scan.nextInt();
//Get the prime factors of the number
ArrayList<Integer> primefactors = get_prime_factors(number);
//Group the factors together and display them on the screen
System.out.print("Prime factors of " + number + " are ");
primefactors.add(0);
for (int a = 0; a < primefactors.size() - 1; a++)
{
if (primefactors.get(a) == primefactors.get(a+1))
{
count++;
}
else
{
System.out.print(primefactors.get(a) + " (" + count + ") ");
count = 1;
}
}
}
}
ほとんどの場合は機能しますが、131033809 を入力すると、奇妙な出力が得られます。
C:\Users\Eamon>java Factorise2
Enter integer to analyse:
4
Prime factors of 4 are 2 (2)
C:\Users\Eamon>java Factorise2
Enter integer to analyse:
128
Prime factors of 128 are 2 (7)
C:\Users\Eamon>java Factorise2
Enter integer to analyse:
9
Prime factors of 9 are 3 (2)
C:\Users\Eamon>java Factorise2
Enter integer to analyse:
121
Prime factors of 121 are 11 (2)
C:\Users\Eamon>java Factorise2
Enter integer to analyse:
131033809
Prime factors of 131033809 are 11447 (1) 11447 (1)
なぜ書かないのか
11447 (2)