Not changing boolean - java

I have a method for testing if a number is a prime number. I have tested the method with 8445, which is not prime because it can be divided by 3. Although the for loop has the 3 as you can see in console, it prints true. That println is in the main method of which I did not take a picture.
public boolean Primzahlerkennen(int i)
{
boolean bool = true;
for (int a = 2; a < i; a ++) {
if (i % a == 0)
bool = false;
else
a++;
if (a==3){
System.out.println("here "+a);
System.out.println(8445%3);
}
}
return bool;
}
Why doesn't the value change to false although 8445 % 3 == 0?

The issue is that you increment a twice, once in the for statement and once in the body of the loop itself.
This causes your loop to skip some divisors (three being one of them).
Further suggestions:
Give your boolean variable a name that reflects its purpose (and not bool).
You don't need to check even divisors other than 2 since none of them are prime.
You can stop the loop at sqrt(i) (figuring out why this is correct is left as an exercise for the reader).

Related

Strange behavior from println

I have not coded in Java in a while. I am finding the first 100 primes that is also a palindrome, now when I run the following code:
public class PalindromPrime {
/**
* Main: Prints out the first 100 PalindromPrimes in tabular format
*/
public static void main (String[] args){
int num = 0;
int myNumber = 2;
int lineCounter = 0;
while(num < 100){
if(isPrime(myNumber)){
num++;
if(lineCounter % 10 == 0){
System.out.print("\n");
}
System.out.println(myNumber);
//System.out.printf("%5d", myNumber);
lineCounter++;
}
myNumber++;
}
}
//Checks if the number is a prime number
public static boolean isPrime(int myNumber){
for(int i = 0; i <= myNumber / 2; i++){
if(i % 2 == 0){
return false;
}
}
return true;
}
}
Java gives me output that frankly does not make any sense to me?? Can someone explain this to me?
-2147483648
-2147483647
-2147483646
-2147483645
-2147483644
-2147483643
-2147483642
-2147483641
-2147483640
-2147483639
-2147483638
-2147483637
-2147483636
-2147483635
-2147483634
-2147483633
-2147483632
-2147483631
-2147483630
-2147483629
-2147483628
-2147483627
-2147483626
-2147483625
-2147483624
-2147483623
-2147483622
-2147483621
-2147483620
-2147483619
-2147483618
-2147483617
-2147483616
-2147483615
-2147483614
-2147483613
-2147483612
-2147483611
-2147483610
-2147483609
-2147483608
-2147483607
-2147483606
-2147483605
-2147483604
-2147483603
-2147483602
-2147483601
-2147483600
-2147483599
-2147483598
-2147483597
-2147483596
-2147483595
-2147483594
-2147483593
-2147483592
-2147483591
-2147483590
-2147483589
-2147483588
-2147483587
-2147483586
-2147483585
-2147483584
-2147483583
-2147483582
-2147483581
-2147483580
-2147483579
-2147483578
-2147483577
-2147483576
-2147483575
-2147483574
-2147483573
-2147483572
-2147483571
-2147483570
-2147483569
-2147483568
-2147483567
-2147483566
-2147483565
-2147483564
-2147483563
-2147483562
-2147483561
-2147483560
-2147483559
-2147483558
-2147483557
-2147483556
-2147483555
-2147483554
-2147483553
-2147483552
-2147483551
-2147483550
-2147483549
Why is it a bunch of negative values??
It is not println that is at fault. It is the logic in your isPrime method.
The number never returns true until the number increments and gets integer overflow, wrapping around to the most negative number, and then the test in the for loop always fails so the function always returns true.
The problem seems to be in the IF statement in the isPrime method.
You are currently referencing i not the number itself.
Change to:
if(**myNumber** % 2 == 0){
return false;
}
Output: 3, 5, 7, 9, ..
The isPrime method needs to be corrected..
public static boolean isPrime(int myNumber) {
for (int i = 2; i < (myNumber / 2) + 1; i++) {
if (myNumber % i == 0) {
return false;
}
}
return true;
}
Now for explanation of the problem...
In your code, instead of checking if number is divisible by index (myNumber % i), you are mistakenly just dividing the index i by 2 (i % 2 == 0) and are checking if it is 0. And since i is always starting count from 0, and the for condition is always satisfied for all positive numbers (i <= myNumber / 2), the loop always starts and returns false as the condition (i % 2 == 0) is always met.
Once myNumber in your main function finally cycles till Integer.MAX_VALUE and then reaches -ve numbers, your condition for loop i <= myNumber / 2 is finally not getting satisfied, and you are getting a true back from the function.
Hence essentially you are printing the 100 numbers counting backwards from Integer.MIN_VALUE
Hope this clarifies. I am sure you were getting results after a wait too..

Prime Number checker is not working

This is the code for a function that is supposed to return true if the input is prime and returns false if it is not.
This is how I intended for it to work: lets say that y = 7, the loop starts with n=1. Since 1(n) is less that 7(y) the loop can iterate. The program checks if y divided by n has a remainder of 0, meaning that n is a factor of y. If it is true, then it checks to see if the factor does not equal 1 or y (7), because if they dont then that means that y has more factors other than its self and 1, meaning that it is not prime, so it should automatically end the function and return false. but since 7 has only two factors, 1 and 7, and they either equal 1 or itself (y) then after the end of the loop, it should return true.
I don't understand why it isn't working.
public static boolean checkIfPrime(long y) {
for ( long n =1L; n <= y; n++) {
if(y%n == 0) {
if( n != 1L || n != y) {
return false;
}
}
}
return true;
}
With a few optimizations the code will be like this
static boolean isPrime(long n){
long lim = (long) Math.sqrt(n);
if(n%2 == 0 && n != 2)
return false;
for (int i = 3; i <= lim; i=i+2)
if(n%i == 0)
return false;
return true;
}
This code:
checks if the number is even and different from 2 (all even numbers
except 2 are compound).
next iterates from 3 to sqrt(n), thats because to prove a number is
prime you don't need to check all the dividers (if you don't believe
me try, and if still don't believe use n/2 wich is enough but not the
minimum value).
For loop pace start from 3 and add 2 in each iteration getting only odd numbers as divder (we first checked that it wasn't an even number).
Remove equal to operator in n <= y. Start your loop from 2. It must be like this. ( long n =2; n < y; n++)
For what you are trying to achieve, pseudo code in my opinion should look like this:
set a flag = true;
Loop from 2 to y-1{
if(y%n==0){
flag = false
break; // Very important
}
}
check flag condition & return (if some othe computation is required) or just return flag
if( n != 1L || n != y) : is adding a check condition unnecessarily to every iteration. try to avoid it.
Why use a flag instead of direct return statement ? Just a preference, a direct return definitely would work in this case.

Why does it matter if I declare a boolean outside vs. inside this while loop?

public class FindPrimes {
public static void main(String[] args) {
int Number_of_prime = 50;
int number_of_final = 10;
int count = 0;
int number = 2;
boolean isPrime = true;
while (count < Number_of_prime) {
for (int divisor = 2; divisor <= number / 2; divisor++) {
if (number % divisor == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
count++;
if (count % number_of_final == 0)
System.out.println(number);
else
System.out.print(number + " ");
}
number++;
}
}
}
The program should find the first 50 prime numbers. When I declare boolean isPrime outside of the while loop (example above) I only get the primes 2 and 3, but when I declare boolean isPrime inside the while loop, I get all 50 prime numbers.
Why is this happening?
I am assuming that you're getting the right answer but you're not sure how/why it is.
Declaring isPrime outside of while does not work. Why? Because if you don't find a prime number within the loop, you set isPrime to false ...and you never reset it back to true ever again. Therefore, any subsequent numbers that come after the non-prime number would automatically default to a non-prime number.
Declaring isPrime inside of while works. Why? Because everytime you find a prime OR non-prime number, you will reset isPrime back to its original value and every subsequent number can and will be evaluated for its prime-ness accordingly.
Try drawing it out if you still have trouble understanding.
Hope that helps.

Prime Number Program Problems

I'm currently working on a program in which the user inputs a number, and the program will give you the number of prime numbers up to that number. Although there are no errors, the program always outputs the same number: 3. This is the code:
public static int Prime(int num){
boolean isPrime = true;
int count = 0;
for (int a = 2; a <=num; a++){
for (int i = 2; i <= a/2; i++){
if (a == 2 || a == 3 || a == 5){
isPrime = true;
}
else if (a % i == 0){
isPrime = false;
}
}
if (isPrime == true)
count++;
}
return count;
}
In your inner for loop, you are setting isPrime, but then you keep looping. Subsequent loops may set isPrime to false if a candidate divisor i doesn't divide cleanly. Only 2, 3, and 5, the 3 numbers in your first if condition, set it to true always, so you always get 3.
Instead, set isPrime to true at the beginning of the inner for loop, and break out of the inner for loop after each time you set isPrime. If the number is 2, 3, or 5, set to true and break so nothing can set it to false, so you can count it. If you found a factor, it's not prime, so set to false and break so nothing can set it to true and it's not counted.
Incidentally, your final if condition tests a boolean; it can be simplified to if (isPrime).
Your strategy is to test each number from 2 through num for primality by scanning for factors other than itself and 1. That's ok, albeit a bit simplisitic, but your implementation is seriously broken.
An approach involving scanning for factors implies that you start by guessing that the number being tested is prime, and then go looking for evidence that it isn't. You've missed the "guessing it's prime" part, which in your particular code would take the form of setting isPrime to true at the beginning of your outer loop.
Your code, on the other hand, never resets isPrime to true after testing the case of a == 5. That variable will be set to false when testing the case of a == 6, and will remain so for the duration. That is why you always get the result 3 for any input greater than 4.
If you properly reset isPrime in the outer loop then you can also remove the first part of the conditional in the inner loop, as it will be redundant. It is anyway never executed in the cases of a == 2 and a == 3 because the inner loop performs zero iterations in those cases.
Note also that it would be more efficient to break from the inner loop as soon as you determine that a is composite, and that you run more iterations of that loop than you need to do for primes (it would be sufficient to loop until i exceeds the square root of a; that is, until i * i > a).
Finally, note that this problem would be more efficiently implemented via the Seive of Eratosthenes (or one of the other prime number seives) as long as the numbers you want to test are not so large that the needed array would be prohibitively large.
I simplified your code by reducing number of operations which is needed to check if a is 2, 3, or 5.
public static int Prime(int num) {
int count = 0;
if (num >= 2) {
count++; // One optimization here
}
for (int a = 3; a <= num; a+=2) { // Another one here as we don't have any even number except 2 :D
boolean isPrime = true;
for (int i = 2; i <= a / 2; i++) {
if (a % i == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
count++;
}
}
return count;
}
#include <iostream>
using namespace std;
int numberOfPrimes(int num)
{
if(num==2)
return 1;
else if(num<2)
return 0;
int prime=1;
for(int i=3;i<=num;i++)
{
for(int j=2;j<=(i/2)+1;j++)
{
if(i%j==0)
break;
if(j==(i/2)+1)
prime++;
}
}
return prime;
}
package com.amit.primenumber;
public class PrimeNumber {
public static void main(String[] args) {
long number=23L;
String message=null;
PrimeNumber primeNumber = new PrimeNumber();
boolean result = primeNumber.primeNumber(number);
if(result){
message="a Prime Number";
}else{
message="Not a Prime Number";
}
System.out.println("The given "+number+" number is "+message);
}
public boolean primeNumber(long number){
for(long i=2;i<=number/2;i++){
if(number%i==0){
return false;
}
}
return true;
}
}
package basics;
public class CheckPrimeOrNot {
public void checkprimeNumber(int i){
int flag=0;
if(i>2){
for(int j = 2; j <= i/2; j++){
if(i%j == 0){
System.out.println("Given number is Not Prime");
flag=1;
break;
}
}
if(flag==0){
System.out.println("Given number is Prime");
}
} else{
System.out.println("Please enter a valid number");
}
}
public static void main(String[] args) {
CheckPrimeOrNot CheckNumber = new CheckPrimeOrNot();
CheckNumber.checkprimeNumber(11);
CheckNumber.checkprimeNumber(0);
CheckNumber.checkprimeNumber(250365);
CheckNumber.checkprimeNumber(1231);
}
}

Can anyone see where the infinite loop in my program is?

The purpose of this program is to find the smallest number evenly divisible by all integers 1 through 20. I know it could be made more efficient, but I'm not interested in optimizing it right now. When I execute the program, it seems to hang forever, which leads me to believe that there's an infinite loop somewhere. I can't seem to find it though. I'm not sure what part of the code is causing the problem and it's relatively concise, so I'll post it all here.
public class Problem5{
public static void main(String[]args){
boolean notFound = true;
while(notFound){
int n = 20;
if(testDivide(n)){
System.out.println(n);
notFound = false;
}
else
n++;
}
}
private static boolean testDivide(int target){
for(int i = 20; i > 0; i--){
if(target % i != 0)
return false;
}
return true;
}
}
If anyone can help me out with this, I'd appreciate it a lot.
Additional Information: The program also never outputs any numbers, which leads me to believe that if(testDivide(n)) is never evaluating to true.
You are initializing the value of n inside your while loop to 20, since n is always 20 for testDivide(20), which will always return false since 20 % 19 != 0 returns false. Hence remove int n = 20 from your while loop.
boolean notFound = true;
while(notFound){
int n = 20;
should be
boolean notFound = true;
int n = 20;
while(notFound) {
your for loop makes sure you return false, and then your while loop always sets i to 20 this is your infinite loop.
See the while loop:
while(notFound){
int n = 20;
if(testDivide(n)){
System.out.println(n);
notFound = false;
}
else
n++;
}
When the while loop is executed first, the value of n is set to 20.
the test divide returns false.
The value of n is decremented to 19.
The loop executes again
The value of of n is reinitialized to 20.
This is the problem initialize n outside the while loop.

Categories

Resources