Some of my prime numbers are coming up as not prime [duplicate] - java

This question already has answers here:
.class expected error in my method and sometimes missing return statement error
(3 answers)
Closed 9 years ago.
Im not too sure whats wrong with my code, it seems like most things are coming up prime.
public static char isPrime(int x)
{
char result = 'r';
for(int y=2;y<x;y++)
{
if(x%y==0)
result = 't';
else
result = 'f';
}
return result;
}

You are always going to the end of the loop so the result will be for x-1.
You need to start with result = 't' and break out of the loop for false values.

When you just toggle like that, you throw away all previous results.
Assume it is prime until you find a composite number
public static char isPrime(int x)
{
char result = 't';
for(int y=2;y<x;y++)
{
if(x%y==0)
{
result = 'f';
break;
}
}
return result;
}

public static char isPrime(int x)
{
char result = 't';
for(int y=2;y<x;y++)
{
if(x%y==0) {
result = 'f';
break;
}
}
return result;
}

Try this:
public static boolean isPrime(int x) {
for (int y = 2; y*y <= x; y++) {
if (x % y == 0)
return false;
}
return true;
}
What was changed:
You should use boolean values to indicate that a condition is true or false, instead of the characters 't' and 'f'.
The biggest problem in your code was that, as soon as you found a divisor for your number (if (x%y==0)) you must break out of the loop, because at this point we're sure that the number is not prime, so there's no point in continuing
Only if no divisors were found, we can return true at the end, outside of the loop

You should break or return after you find out that your number is not a prime, simple as that. Additionally it seems that you return t when the number is NOT a prime.

Please use boolean and provide an Junit testcase, so we know what you exactly expect.
public static boolean isPrime(int x)
{
for(int y=2;y<x;y++)
{
if(x%y==0)
return false;
}
return true;
}

Your true and false are reversed, if its exactly divisable by something its not prime
Also, you're overwriting all your old data on each run through the loop, as soon as anything is exactly divisible then its not prime, return false at that point
Also, have you considered using the booleans true and false?

You method is not resolving prime numbers. A number is a prime if it can only be divided by one or itself.
If I input 17 into your method, for example, the result will be set to 'f' when y == 16, and that will be the returned result. However, 17 is a prime number.
You should instead try something like
for (int i = 2; i < x; i++) {
if (x % y == 0) return false;
}
return true;

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..

Getting weird output while finding prime number in java

I have two methods to find out prime number in java method - 2 working fine but getting wrong output from method one, can any help me where i did wrong in logic. Thanks in advance
My entire code
package prepare;
import java.util.Scanner;
public class Squar {
//Method - 1 to find prime number
boolean isPrime(int num){
int exp = (int)Math.sqrt(num);
for(int i=2;i<exp;i++){
if(exp%2==0){
return false;
}
}return true;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int num = scan.nextInt();
Squar s = new Squar();
System.out.println("From M1 "+s.isPrime(num));
scan.close();
System.out.println("From M2 "+s.isPrimeNumber(num));
}
//Method - 2 to find prime number
public boolean isPrimeNumber(int number) {
if(number == 1){
return false;
}
if (number == 2 || number == 3) {
return true;
}
if (number % 2 == 0) {
return false;
}
int sqrt = (int) Math.sqrt(number) + 1;
for (int i = 3; i < sqrt; i += 2) {
if (number % i == 0) {
return false;
}
}
return true;
}
}
for input : 63 actual out put would be false in prime number but getting
different output from method one
output
63
From M1 true
From M2 false
In isPrime() method, Shouldn't you be checking num % i == 0 rather than exp % 2 == 0?
Change isPrime function like this.
boolean isPrime(int num) {
int exp = (int) Math.sqrt(num);
for (int i = 2; i < exp; i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
Because in if condition you are checking exp%2 == 0 . But this statement does not change when iterating on i < exp. So this logic should be on with num % i == 0
Have a look at this line of your code
if(exp%2==0){
it should be num % i
Well I think the culprit is
if(exp%2==0){
and it is causing a problem while iterating i<exp.So you may want to tweak it to
num%i==0
I have tried to give a few other approaches to this issue.
I hope that would be helpful.
I think there is a reason that tempted you to use
(int)Math.sqrt(num);
I have tried to elaborate it below.
Consider below 3 approaches.
All of them are correct but the first 2 approaches have some drawbacks.
Approach 1
boolean isPrime(int num) {
for(int i=2;i<num;i++) {
if(num%i==0)
return false;
}
return true;
}
We have a scope to make it faster.
Consider that if 2 divides some integer n, then (n/2) divides n as well.
This tells us we don't have to try out all integers from 2 to n.
Now we can modify our algorithm:
Approach 2
//checks whether an int is prime or not.
boolean isPrime(int num) {
for(int i=2;2*i<num;i++) {
if(num%i==0)
return false;
}
return true;
}
Finally, we know 2 is the "oddest" prime - it happens to be the only even prime number.
Because of this, we need only check 2 separately, then traverse odd numbers up to the square root of n.
I think this might have tempted you to use (int)Math.sqrt(num);
Approach 3
//checks whether an int is prime or not.
boolean isPrime(int num) {
//check if num is a multiple of 2
if (num%2==0) return false;
//if not, then just check the odds
for(int i=3;i*i<=num;i+=2) {
if(num%i==0)
return false;
}
return true;
}
Hence, we've gone from checking every integer (up to n to find out that a number is prime) to just checking half of the integers up
to the square root.
Is it not an improvement, especially considering when numbers are large.
Well, your first algorithm is almost (replace %2 with %i) correct. I do not know the second algorithm, but i would definitely change it to this form:
public boolean isPrime(int n) {
if (n <= 1) {
return false;
}
for (int i = 2; i < Math.sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}

logical OR in Java not working?

I am still very new to Java and I am struggling a bit trying to understand why does my code only return "false" when modulo is not equal to 0, ignoring the two other cases, so when divisor is 0 and when the array is empty.
In case of divisor = 0, I get java.lang.ArithmeticException: divide by zero
For some reason empty array IS divisible by 0, how could that be?
Any help highly appreciated, thanks!
public boolean Divisible(ArrayList<Integer> array1, int divisor) {
int i;
int modulo;
boolean isDiv=true;
for(i=0; i<arr.size(); i++){
modulo=((arr.get(i)%divisor));
i++;
if(modulo!=0 || divisor==0 || arr.isEmpty())
{
isDiv= false;
break;
}
}
return isDiv;
}
Before you do anything check for an empty List or a 0 divisor.
if(divisor==0||array1.isEmpty()){
return false;
}
Then you can check the list.
for(Integer i: array1){
if(i%divisor!=0){
return false;
}
}
Finally.
return true;
The main problem is that you're executing the OR check inside the for loop, but if the for loop iterates 0 times the condition is never checked, so the problem you're experiencing.
Here is a modified version of your function, where I moved the check conditions outside the for loop:
public boolean Divisible(ArrayList<Integer> array1, int divisor)
{
int i;
int modulo;
boolean isDiv = true;
if(array1.isEmpty()) // Check array1.isEmpty() outside for loop.
{
isDiv = false;
}
else if(divisor == 0) // Check divisor outside for loop.
{
isDiv = false;
}
else
{
for(i = 0; i < arr.size(); i++)
{
modulo = (arr.get(i) % divisor);
// i++; i is already increased by for instruction.
if(modulo!=0 /*|| divisor==0 || arr.isEmpty()*/) // Only modulo must be checked here.
{
isDiv= false;
break;
}
}
}
return isDiv;
}

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);
}
}

Method to check if number is symmetric in Java [duplicate]

This question already has answers here:
How do I check if a number is a palindrome?
(53 answers)
Closed 9 years ago.
I need help with a method to check if a number is symmetric, so from what I understand I need to check equality between all the numbers and to make sure there is no different number amounts them...right?
This is my code:
public boolean isSemetric (int number) {
int temp;
boolean answer = true;
while (number != 0) {
temp = number % 10;
number /= 10;
if (temp != (number%10)) {
answer = false;
} else {
answer = true;
}
}
return answer;
}
I'm kind of new to programming so be forgiven to my code :/
Thanks!
As peter.petrov pointed out in the comment section of your question, your method as it's written will always return false, except for when number is equal to 0. The reason for this can be seen when you pass in a number like 111 and step through the code in a debugger. The final iteration will fail because number /= 10 will result in 0, and temp will be 1, which fails your test.
If you are indeed looking to identify palindromes, consider the following approach that should be simple to implement
1. copy number into temp
2. convert temp to a String, and reverse it (tmpStr)
3. convert tmpStr back to an integer (reversedInt)
4. compare number and reversedInt for equality
viola. Not the most efficient algorithm, but its easy to understand and gets the job done.
I would do it like this (I don't want to use String here and I don't want to use local array variable for the digits).
public static boolean isSymmetric (long number) {
if (number == 0) return true;
else if (number < 0) return false;
long DEG_10 = (long)(Math.pow(10, (int)Math.log10(number)));
while (number > 0){
long dStart = number / DEG_10;
long dEnd = number % 10;
if (dStart != dEnd) return false;
number = (number - dStart * DEG_10 - dEnd) / 10;
DEG_10 /= 100;
}
return true;
}
This is the easiest approach I can think of - Get the String value of the number, if the reverse is the same then it is symmetrical.
// Symmetry
public static boolean isSymmetric(int number) {
String val = String.valueOf(number); // Get the string.
StringBuilder sb = new StringBuilder(val);
return (val.equals(sb.reverse().toString())); // if the reverse is the same...
}
Here's a somewhat fixed up version of your code. However, it checks if all numbers are the same, e.g. 5555 or 111. 11211 would return false.
public boolean areAllDigitsTheSame (int number) {
int temp;
boolean answer = true;
while (number >= 10) {
temp = number % 10;
number /= 10;
if (temp != (number%10)) {
return false
}
}
return true;
}
Edit: The C++ answer in the linked question works by constructing the reverse number gradually in the loop, and finally checking if they're the same. This is a similar to what you are doing.
Here's another version for fun:
public boolean isPalindrome (int number) {
int reversedNumber = 0;
while (number > 0) {
int digit = number % 10;
reversedNumber = reversedNumber*10 + digit;
if (reversedNumber == number) { // odd number of digits
return true;
}
number /= 10;
if (reversedNumber == number) { // even number of digits
return true;
}
}
return false;
}

Categories

Resources