# Need Help - Factoring & Prime Finding Code

Printable View

• November 4th, 2009, 11:39 PM
prodigytoast
Need Help - Factoring & Prime Finding Code
Hello, I'm working on a project that outputs the numbers 2 – 100.
Next to each number, it should list all the factors for that number.
If the number has no factors, it should print prime.
Ex.
2 prime
3 prime
4 2
5 prime

Having some difficulty so far. I'm aware I need to use loops, but I'm not sure what to %, and by what to determine if it's a factor.

This is my fail code so far: (I realize its horrible and is incomplete)
Code :

```public class Prime { public static void main(String[] args) { findPrime(factors()); factors(); } public static void findPrime(int k) { int i = 2; int ans = i%k; while(i<=100) { System.out.println(ans); i++; }   } public static int factors() { int k = 1; for(k = 1; k <=100; k++) { } return k; } }```

Any help whatsoever is greatly appreciated. Thanks!
• November 5th, 2009, 12:09 AM
helloworld922
Re: Need Help - Factoring & Prime Finding Code
mmm... prime numbers :(

The easiest way to do this is probably seeing if for some number 1<n<101, printing out any numbers that n%i == 0 (where i is a number from 2 to n-1). If nothing was printed out, then print out prime. You can keep track of nothing being printed out by having a boolean flag to denote the primality of the number.

Code :

```for (int n = 2; n <= 100; n++) { boolean isPrime = true; // assume n is prime System.out.print(n + " : "); for(int i = 2; i < n; i++) { if (n%i == 0) { System.out.print(i); isPrime = false; } } if (isPrime) { System.out.println("Prime"); } else { System.out.println(""); // go to next line }```
• November 5th, 2009, 12:15 AM
prodigytoast
Re: Need Help - Factoring & Prime Finding Code
Thanks alot! That helped me so much, I appreciate it, however, I need to work on the factoring part now, with that current code, it is printing some pretty strange numbers next to the non-prime numbers.
Ex.
Quote:

27 : 39
28 : 24714
29 : Prime
30 : 23561015
31 : Prime
32 : 24816
33 : 311
34 : 217
35 : 57
36 : 234691218
37 : Prime
• November 5th, 2009, 12:29 AM
helloworld922
Re: Need Help - Factoring & Prime Finding Code
ahh, forgot... it's not printing out any spaces between the numbers :P
• November 5th, 2009, 12:30 AM
prodigytoast
Re: Need Help - Factoring & Prime Finding Code
Oh! haha I didn't realize those were factors! Thanks again!
• November 5th, 2009, 07:38 AM
Freaky Chris
Re: Need Help - Factoring & Prime Finding Code
lol nice one helloworld, always leave something out to confuse them. If it's solved coud you please mark it as so.

Thanks,
Chris