Results 1 to 4 of 4
- 08-21-2012, 08:12 PM #1
Member
- 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! =)
- 08-21-2012, 08:36 PM #2
Senior Member
- Join Date
- Oct 2011
- Location
- Sweden
- Posts
- 123
- 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 for-loop 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 for-loop as long as int i is less or equal to your specified integer.
I guess that adding a simple " = " in your for-loop will give you the correct results.
Java Code:for (int i = 2; i <= input; i++)
Cheers,
Z!
- 08-21-2012, 09:00 PM #3
Member
- 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.
- 08-21-2012, 09:10 PM #4
Senior Member
- Join Date
- Oct 2011
- Location
- Sweden
- Posts
- 123
- Rep Power
- 0
Similar Threads
-
Big prime
By diamonddragon in forum New To JavaReplies: 25Last Post: 02-02-2012, 11:04 PM -
Prime Factorization
By skaterboy987 in forum New To JavaReplies: 7Last Post: 10-27-2011, 01:18 AM -
Prime Number - System print all the prime numbers ...
By pinkdreammsss in forum New To JavaReplies: 20Last Post: 04-26-2009, 01:50 AM -
Prime numbers
By tercius in forum New To JavaReplies: 3Last Post: 05-04-2008, 06:05 AM -
Prime numbers
By gapper in forum New To JavaReplies: 3Last Post: 02-07-2008, 10:09 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks