Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

prime factorization

807600Oct 7 2007 — edited Oct 20 2007
there is a small problem with the output of my code. if 'n' for example is 22, it prints
"22 is composite, it is 2 * 11 * ".
but it should be
"22 is composite, it is 2 * 11".

does anyone know what i need to change to fix this?
class PrimeFactorization { 

    static String PFactors = "";

    public static void main(String[] args) {
        for(int n = 2; n <=100; n++) {
	    if(isComposite(n)) System.out.println(n+" is composite, it is "+PFactors);
	    else System.out.println(n+" IS A PRIME NUMBER");
	}
    }

    static boolean isPrime(int n) {
	if(n < 2) return false;
	for(int d = 2; d <n; d++) {
	    if(n%d == 0) return false;
	}
	return true;
    }

    static boolean isComposite(int n) {
        PFactors = "";
	int sum = n, d = 2;
	while(sum !=1) {
	    if(isPrime(d) && sum%d == 0) {
	    sum /= d;
	    PFactors +=d+" * ";
	    }
	    else d++;
        } 
	return n != d;
    }
}


// 22/2 = 11. 11/11 = 1.  (2*11).
// 100/2 = 50. 50/2 = 25. 25/5 = 5. 5/5 = 1. (2*2*5*5).
// 333/3 = 111. 111/3 = 37. 37/37 = 1. (3*3*37).
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Nov 17 2007
Added on Oct 7 2007
22 comments
102 views