Not outputting answer - console blank , no errors given, Java - java

I am new to coding in Java so I am practicing with the Euler Projects to get into it. I am using Eclipse and my issue is that code that to my eyes should work fine doesn't work. I don't get an error, but nothing outputs to the console either. The console is blank.
This is my code for question 5:
/*
2520 is the smallest number that can be divided by each of the numbers
from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all
of the numbers from 1 to 20?
*/
class main {
public static void main(String[] args) {
int i = 2520;
int biggestNum = 0;
while (biggestNum != i) {
for (int j = 1; j <= 20; j++) {
if (i%j != 0) {break;}
if (j == 20) {biggestNum = i; }
}
i++;
}
System.out.println(biggestNum);
}
}
and this is the code for question 3:
/*
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
*/
public class euler3 {
public static boolean isPrime (long num) {
for (long i = 2; i < num; i++) {
if (num % i == 0 ) return false;
}
return true;
}
public static void main(String[] args) {
long num = 600851475143L;
long x = 1;
for (int i = 2; i <= num; i++) {
if (num % i == 0) {
if (isPrime(i)) {
x = i;
}
}
}
System.out.println(x);
}
}
The thing with question 3, though, is that it works for the small number (13195) and it gives me 29, but I get the blank console again for the larger one.
I decided to include both of these questions since they have the same problem of not outputting my answer to the console. Any help would be appreciated.

I decided to include both of these questions since they have the same problem of not outputting my answer to the console. Any help would be appreciated.
Welcome to stackoverflow. When debugging your code, be sure to do so one at a time. Just because both programs aren't displaying the output that you expect doesn't mean that they have the same issue.
There are many ways to debug your buggy code. You can do "printf" style debugging by placing System.out.println(...) statements inside of your loops so you can see what is happened or your can use a Java debugger. The 2nd answer can often get a faster result in terms of finding the problem but you need to learn about debuggers and it depends on which IDE you are using.
When you get more experienced, being able to execute the code in your head really helps with bugs as these. For example, I can look at your code and see:
for loop is going from 2 to 600851475143L
tests if the number if prime
sets x to be the number if it prime.
continue. OH it's not breaking from the loop.
You have to go step by step through your code either in your head, with a debugger, or by walking through debug output to find these sorts of bugs.
Best of luck.

Related

I dont understand how this is deciding what is and isn't a prime number

Very new to programming here, trying to get my head around how this is works and I just cannot seem to do it, spent a good while staring at this one.
code already works, I Just do not fully understand.
class PrimeNum{
public static void main(String[] args) {
int a;
int b;
boolean isprime;
System.out.println("this is a program listing prime numbers up to 100");
for(a = 2; a < 100; a++){
for(b=2; b <= a/b; b++)
```if((a%b) == 0) isprime = false;```
if(isprime)
System.out.println(a + " is prime.");
}
}
}
I think that i understand both for lines, please correct me If I am wrong.
Am I correct in saying that, if a is less than 100, increment
if b is less than or = to a/b then increment again which it always will be
the line that i don't understand is highlighted in particular, what is the need for the ==0?
I just cannot seem to grasp the concept that is happening here and how its figuring out what is and isn't prime.
Okay, we'll start up:
public static void main(String[] args){..}
This is the main method which every Java program should have. You'll get to learn user-defined methods, but that's for later;
We'll skip the variable declaration...
for(a = 2; a < 100; a++){...
}
This first loop gets you a number for deciding for its prime being...
for(b=2; b <= a/b; b++)
if((a%b) == 0)
isprime = false;
Probably b is for division of a...
So if you execute this 6 times for number 2,
it'll go that way, if the remainder got on dividing 2 is zero or not.
Here, it is till 100. And the logic is such that the divisor will be less than or equal to dividend(b <= a/b).
SO a%b == 0 means that if a is divided by b and if remainder is zero, then it is a prime 'cause prime numbers have no factors rather than 1 and the number itself.
Hope you're clear about this.
SO keep calm, code and HIT A UPVOTE OR COMMENT IF SOMETHING IS WRONG!

Why is this program for finding Prime Factors of a number using Java not working?

I would like to know why this java program is not working to find the prime factors of a number. I have seen many solutions on this site and elsewhere but I want to know why this approach is not sufficient as it returns only 1 as an output? The first "if statement" handles numbers from 1 and lower to return -1 (invalid value), thanks.
public class PrimeFactors{
public static void main(String[] args) {
System.out.println(getPrimeFactors(4));
}
public static int getPrimeFactors(int number) {
if (number <= 1) {
return -1;
}
for (int i = 1; i <= number; i++) {
if (number % i == 0) {
return i;
}
}
return number;
}
}
The code you have here is returning the value of i, which you have set to 1. You don't have enough understanding of how you would find a prime number based on your code. No matter what you put into your method, getPrimeFactors will either return -1 or 1, because of how your code is set up. The remainder when a number is divided by 1 is always 0, therefore it is always true, which will just return 1. And if the number is less than or equal to 1, it will return -1. Return number is essentially dead code unless you fix the syntax. Hope this helps you out!

sum of n prime numbers java, confused

I've read several posts on this, I even did this during one of my exams, but was in vb.net. It worked fine, however eclipse is just running non-stop when I try to execute my program, or otherwise it gives me the wrong answer. Here is my fourth attempt at it. I need to add the sum of the first n prime numbers, hence I do a check for whether a number is prime or not. The loop does not stop for some reason. Any help would be appreciated. Thanks.
int count = 0;
int noMod0s = 0;
int total = 0;
//static boolean prime;
for (int y = 2;count<5;y++) {
for (int z = 1;z<y;z++) {
if (y % z == 0) {
noMod0s++;
}
}
if (noMod0s == 1) {
total = total + y;
count++;
noMod0s = 0;
}
}
System.out.println(total);
There are at least two issues with your code:
You are not resetting variable noMod0s for each separate primality test. You should do it before the second loop.
The second loop should start from 2 not 1 to be a valid primality test. Of course in this case you will be comparing noMod0s == 0. It works the same but it gives a clearer idea of what the code is doing.

What is wrong with this prime factorization code in Java?

I was trying to make a method to do the prime factorization of a number, and it's probably not the most efficient, but I don't see why it shouldn't work.
public static ArrayList<Integer> primeFactorize(int num) {
ArrayList<Integer> primeFactors = new ArrayList<Integer>();
for (int i = 2; i < Math.sqrt((double) num); i++) {
if (isPrime(i) && factor(num).contains(i)) {
primeFactors.add(i);
num /= i;
if (isPrime(num)) {
primeFactors.add(num);
break;
}
i = 2;
}
}
return primeFactors;
}
It calls upon two other methods that I wrote named factor() and isPrime(), which do exactly what you would expect them to (returns an ArrayList of factors and either true or false depending on if the input is prime, respectively).
I went through the debugger with num being 12, and it worked fine for the first loop, where it added 2 to primeFactors. However, when it got to the top of the array again with num being 6 and i being 2, it exited the loop as if i < Math.sqrt((double) num) returned false.
But that wouldn't make sense, because the square root of 6 is a bit over 2. I also tried (double) i < Math.sqrt((double) num), but it just did the same exact thing.
Can anyone see what I'm missing? Thanks for any replies.
EDIT: Here is my code now, thanks for the help! I know for sure I could make it more efficient, so I might do that later, but for now this is perfect.
public static ArrayList<Integer> primeFactorize(int num) {
ArrayList<Integer> primeFactors = new ArrayList<Integer>();
int i = 2;
while (i < Math.sqrt((double) num)) {
if (isPrime(i) && num % i == 0) {
primeFactors.add(i);
num /= i;
if (isPrime(num)) {
primeFactors.add(num);
break;
}
i = 2;
}
else
i++;
}
return primeFactors;
}
In your for loop, the i++ section will get called at the end of every loop. So in your code, you set i equal to 2. Then, the loop ends, and adds 1 to i, making it be 3. Then the comparison happens, and 3 is more than sqrt(6), so the loop exits.
If you want i to be 2 in the next iteration, you need to set it to a value so that after the increment operation runs it will be 2, not before; in this case, you should set it to 1. A better solution would be to change your code structure so it's not necessary though. As pointed out by biziclop, a while loop will let you decide whether or not to increment, and will avoid this problem.
Since you already accepted an answer I assume your problem is solved. The thing I want to point out is that casting integers to doubles is generally a bad idea if there is another way. Therefore I want to show you the below implementation, which doesn't use floating-point arithmetic. Also I think it's a bad idea to check whether or not num is a prime number, because this slows down the algorithm. Moreover if num % i == 0 evaluates to true, i is always a prime number, thus the isPrime(i) check is superfluous and also slows down your algorithm.
List <Integer> primeFactors(int n) {
List<Integer> factors = new ArrayList<>();
for (int i = 2; i <= n / i; ++i) {
while (n % i == 0) {
factors.add(i);
n /= i ;
}
}
if (n > 1) {
factors.add(n);
}
return factors ;
}

Java - Can't make ProjectEuler 3 Work for a very big number (600851475143)

Resolution:
It turns out there is (probably) "nothing wrong" with the code itself; it is just inefficient. If my math is correct, If I leave it running it will be done by Friday, October 14, 2011. I'll let you know!
Warning: this may contain spoilers if you are trying to solve Project Euler #3.
The problem says this:
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
Here's my attempt to solve it. I'm just starting with Java and programming in general, and I know this isn't the nicest or most efficient solution.
import java.util.ArrayList;
public class Improved {
public static void main(String[] args) {
long number = 600851475143L;
// long number = 13195L;
long check = number - 1;
boolean prime = true;
ArrayList<Number> allPrimes = new ArrayList<Number>();
do {
for (long i = check - 1; i > 2; i--) {
if (check % i == 0) {
prime = false;
}
}
if (prime == true && number % check == 0) {
allPrimes.add(check);
}
prime = true;
check--;
} while (check > 2);
System.out.println(allPrimes);
}
}
When number is set to 13195, the program works just fine, producing the result [29, 13, 7, 5] as it should.
Why doesn't this work for larger values of number?
Closely related (but not dupe): "Integer number too large" error message for 600851475143
The code is very slow; it is probably correct but will run for an unacceptably large amount of time (about n^2/2 iterations of the innermost loop for an input n). Try computing the factors from smallest to largest, and divide out each factor as you find it, such as:
for (i = 2; i*i <= n; ++i) {
if (n % i == 0) {
allPrimes.add(i);
while (n % i == 0) n /= i;
}
}
if (n != 1) allPrimes.add(n);
Note that this code will only add prime factors, even without an explicit check for primality.
Almost all the Project Euler problems can be solved using a signed datatype with 64 bits (with the exception of problems that purposefully try to go big like problem 13).
If your going to be working with primes (hey, its project Euler, your going to be working with primes) get a headstart and implement the Sieve of Eratosthenes, Sieve of Atkin, or
Sieve of Sundaram.
One mathematical trick used across many problems is short circuiting finding factors by working to the square root of the target. Anything greater than the square corresponds to a factor less than the square.
You could also speed this up by only checking from 2 to the square root of the target number. Each factor comes in a pair, one above the square root and one below, so when you find one factor you also find it's pair. In the case of the prime test, once you find any factor you can break out of the loop.
Another optimization could be to find the factors before checking that they are prime.
And for very large numbers, it really is faster to experiment with a sieve rather than brute forcing it, especially if you are testing a lot of numbers for primes. Just be careful you're not doing something algorithmically inefficient to implement the sieve (for example, adding or removing primes from lists will cost you an extra O(n)).
Another approach (there is no need to store all primes):
private static boolean isOddPrime(long x) {
/* because x is odd, the even factors can be skipped */
for ( int i = 3 ; i*i <= x ; i+=2 ) {
if ( x % i == 0 ) {
return false;
}
}
return true;
}
public static void main(String[] args) {
long nr = 600851475143L;
long max = 1;
for ( long i = 3; i <= nr ; i+=2 ) {
if ( nr % i == 0 ) {
nr/=i;
if ( isOddPrime(i) ){
max = i;
}
}
}
System.out.println(max);
}
It takes less than 1 ms.

Categories