0

Alright so I'm trying to set up a program that will find prime numbers. I've set up an array called primes with prime numbers up to 199. How can I create a while loop that pretty much says, while (x%primes[any number in primes] <= 0). I'm not sure what I should be putting to make it properly detect it. I know or statements are an option, I'm just wondering if there's a better way. Here's my code:

import static java.lang.System.out;
public class Problem3 {

public static void main(String[] args) {
    /// What is the largest prime factor of the number 600851475143 ?
        long x;
        x = 600851475143L;
        int[] primes = {
            2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199,
        };
        out.println(x);
        //while (x % primes[*This is where I need clarification*] <= 0) {
            int i = 0;

                for (i = 0; i < primes.length; i++) {
                    //out.println("Term " + i + " is " + primes[i]);
                        if (x%primes[i] <=0) {
                            x = x/primes[i];
                        }

                }   
        //}

        out.println(x);

}

}

This answer worked for me!

4
  • What should the while loop do? Its not clear Commented Dec 29, 2018 at 8:33
  • @Sand my apologies. I needed the while loop to be active while the the main number was still divisible by a number in the array. I had set it up pretty funky though and another user helped me out! Commented Dec 29, 2018 at 8:56
  • Its fine and good to know it has been resolved Commented Dec 29, 2018 at 8:58
  • @Morgan Please post an answer to your own question with the solution. Commented Dec 29, 2018 at 9:06

1 Answer 1

1

Your table of primes is too small (only 71 is a factor of 600851475143L). Easiest fix, eliminate that table and iterate from three to the square root of your number incrementing by two. Like,

long x = 600851475143L;
for (int i = 3; i <= Math.sqrt(x); i += 2) {
    if (x % i == 0) {
        System.out.println(i);
        x /= i;
    }
}
System.out.println(x);

I get

71
839
1471
6857

And

71*839*1471*6857
600851475143
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.