Projecteuler.net – Problem 3 – Java

http://projecteuler.net/problem=3

I played around with creating a function for prime factorization that I can carry forward for future problems. Needs minor work to catch numbers that you shouldn’t pass to it. I’m also playing with JavaDoc as well. Still trying to get the hang of breaking down my code into pieces that work well for Java.

	/***
	 * Prime Factorization of positive long int greater than 1.
	 * Ex: The Prime Factorization of 8 returns [2, 2, 2]. (2 * 2 * 2 = 8 )
	 * @param 	num 	long int
	 * @return 	ArrayList <Long>
	 */
	public static ArrayList <Long> get_prime_factorization(long num) {
		ArrayList<Long> prime_factors = new ArrayList<Long>();

		// define a maximum search range, result is truncated
		long maximum = (num / 2);

		for (long i = 2; i <= maximum; ++i) {
			if (num%i == 0) {
				prime_factors.add(i);

				// reduce the range the loop searches based on the prime factor that is found
				num = num / i;
				i = 1;
				maximum = num / 2;
			}
		}
		prime_factors.add(num);

		return prime_factors;
	}
This entry was posted in Java, Project Euler. Bookmark the permalink.

Leave a Reply