L Brunot - 8 months ago 23

Java Question

Here is what I am looking to do. I have included my code below my goal for your reference.

Goal: Find Prime Factorizations of a number n. Then concatenate the prime factors into one number, x. Then Take that number, x, and divide by n. If x%n = 0, print True. If x%n != 0, print false. (i.e. if n = 100, Prime Factors are 2,2,5,5. Turn into an integer 2255, then take 2255/100. 2255%100 != 0, Print False. )

What I have now prints out “2 2 5 5” and prints out all prime factors correctly for any n that I put in.

If possible, ideally I would like to run this for numbers k= 2 through any upper bound I set, call the upper bound U, and if any value for k = 2 through U yields a result that is true (from above) Then I would like to print that k value.

`import acm.program.*;`

import acm.util.*;

import java.util.Scanner;

// -------------------------------------------------------------------------

public class Factors extends ConsoleProgram

{

//~ Instance/static variables .............................................

private RandomGenerator rgen = RandomGenerator.getInstance();

//~ Constructor ...........................................................

// ----------------------------------------------------------

/**

* Creates a new ForLoops object.

*/

public void run()

{

int n = 100;

println("The prime factorization of " + n + " is: ");

// for each potential factor i

for (int i = 2; i*i <= n; i++) {

// if i is a factor of N, repeatedly divide it out

while (n % i == 0) {

n = n / i;

print(i+" ");

//print(i/n);

}

}

// if biggest factor occurs only once, n > 1

if (n > 1) println(n);

else println();

}

}

Answer

If you have an over-arching for-loop that your existing code goes in like so:

```
int U = 10; //or whatever your limit is
for (int j = 2; j < U; j++) {
}
```

And you incorporate your algorithm for finding the prime factors by having a StringBuilder that you add your factors to:

```
StringBuilder factors = new StringBuilder();
```

Which you could use like this to add your factors:

```
for (int i = 2; i * i <= n; i++) {
// if i is a factor of N, repeatedly divide it out
while (n % i == 0) {
n = n / i;
factors.append(Integer.toString(i));
print(i + " ");
}
}
```

Then you could parse your factors.toString like so:

```
int newNumber = Integer.parseInt(factors.toString);
```

Which would give you your number (like 2255 for example). This could then just be put in an if-statment that says "if this number is evenly divisible by n, then print n":

```
if ( newNumber % n == 0 ){
System.out.println(n);
}
```

This should at least help you get on your way.