Results 1 to 4 of 4
 08212012, 08:12 PM #1Member
 Join Date
 Aug 2012
 Posts
 2
 Rep Power
 0
Can not see why this Prime factorization is not working
Here's my code:
import java.util.*;
public class FactorsOfAnInteger {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
int input = 0;
System.out.println("Enter an integer: ");
input = console.nextInt();
for (int i = 2; i < input; i++) {
while (input % i == 0){
System.out.print(i + " ");
input /= i;
}
}
System.out.println();
}
}
It compiles fine and even properly factors SOME integers but not for all. For example, when I enter 16, I get the correct answer 2 2 2 2 or if I enter 150 I get 2 3 5 5 which is correct. However when I start to use other simple numbers like 80 I get 2 2 2 2 which is incorrect or when I type 9684 i get 2 2 3 3 which is also incorrect. Is there a logic error that I am missing?
Thanks for any help in advance! =)
 08212012, 08:36 PM #2Senior Member
 Join Date
 Oct 2011
 Location
 Sweden
 Posts
 124
 Rep Power
 0
Re: Can not see why this Prime factorization is not working
Hello falco,
please use the [CODE]tags when posting code to maintain the Java highlighting and the structure of your code.
Judging by your code, your forloop is running as long as your int i is less than your specified integer to factorize, which obviously will give you the wrong result since you need to run the forloop as long as int i is less or equal to your specified integer.
I guess that adding a simple " = " in your forloop will give you the correct results.
Java Code:for (int i = 2; i <= input; i++)
Cheers,
Z!
 08212012, 09:00 PM #3Member
 Join Date
 Aug 2012
 Posts
 2
 Rep Power
 0
Re: Can not see why this Prime factorization is not working
Thank you very much, ugh such a simple mistake Sorry my first post, I'll add the [CODE] tag next time.
 08212012, 09:10 PM #4Senior Member
 Join Date
 Oct 2011
 Location
 Sweden
 Posts
 124
 Rep Power
 0
Similar Threads

Big prime
By diamonddragon in forum New To JavaReplies: 25Last Post: 02022012, 11:04 PM 
Prime Factorization
By skaterboy987 in forum New To JavaReplies: 7Last Post: 10272011, 01:18 AM 
Prime Number  System print all the prime numbers ...
By pinkdreammsss in forum New To JavaReplies: 20Last Post: 04262009, 01:50 AM 
Prime numbers
By tercius in forum New To JavaReplies: 3Last Post: 05042008, 06:05 AM 
Prime numbers
By gapper in forum New To JavaReplies: 3Last Post: 02072008, 10:09 AM
Bookmarks