the output of 2nd for loop - java

i have this code here and I am having a really hard time to figure out that isn't when i == 6 that would result in two results in the second loop when 6%2 = 0 and 6%3 = 0 and 6%4 =2. so how the compiler decides which if 6 is a prime number or not
public static void main(String[] args) {
for (int i = 2; i < 100 ; i++) {
if (isPrime(i))
System.out.println(i);
}
}
private static boolean isPrime(int n) {
for (int i = 2; i < n; i++){
if (n % i == 0)
return false;
}
return true;
}

I am assuming that you are asking how the second loop knows 6 is prime or not.
In the second loop, if n is 6 then the loop will run once and then return false since 6%2==0. It will not check 6%3, 6%4 because the return statement was already called.
Basically, if the condition n%i== 0 is met, the return statement is called so no more values are checked. Remember that for prime numbers n%i == 0 can never be true anyways so there is no point in checking any other values.

This code prints every odd number as "prime" because the isPrime method will return false if (n%2 == 0) (first iteration), and true otherwise.
You could change your method to something like:
public static void main(String[] args) {
for (int i = 2; i <100 ; i++) {
if (isPrime (i))
System.out.println(i);
}
}
private static boolean isPrime(int n) {
for (int i =2; i< n; i++)
if (n%i == 0)
return false;
}
return true;
}

Related

Return a boolean value using if/else in java

I am trying to write a code to check if a number is prime and return true if it is a prime number using if/else statement.
I am giving the code below, I have written.
It is always showing an exception "missing return statement".
class Main
{
static boolean isPrime(int x)
{
for(int i = 2;i <= x/2;++i)
{
if(x%i == 0)
{
return false;
}
else
{
return true;
}
}
}
public static void main (String args[])
{
boolean prime = isPrime(11);
System.out.println(prime);
}
}
The problem in your code is that you are returning true the first time the modulus is not 0. That's wrong, because you have to make sure that x is not divisible to any of the numbers in range [2, x/2].
Modify your method as follows:
static boolean isPrime(int x)
{
if(x <= 1)
{
return false;
}
boolean ret = true;
for(int i = 2;i <= x/2;++i)
{
if(x%i == 0)
{
ret = false;
break;
}
}
return ret;
}
In this way you break as soon as you are sure the number is not prime. If it's prime it will complete the loop without finding non-zero remainders.
The x<=1 scenarios is the cause of the warning you are experincing, as with those inputs your method exits without encountering a return statement. I just checked for this condition at the beginning of the function.
Finding prime numbers
I just suggested the fix to your isPrime implementation, which is the simpliest way to find prime numbers. Anyway there are smarter ways to find them:
The Siege of Eratosthenes method
You could check only odd numbers, saving half the time
You could check if x belongs to the 6*x±1 set. In fact all prime numbers from number 5 follow this rule
You are not taking into account that the number "x" passed into the method can be zero. If that is the case (x == 0) you loop will not execute and there is a path through the method that does not return TRUE or FALSE.
As explained before, in the existing implementation it is possible that loop is not executed and no return statement is provided after the loop.
Better search for prime numbers would be:
Check for 0 and 1 to return false for them
Check for even numbers: all even numbers except 2 are composite
Check only odd numbers for primality
Check limited range of numbers using "inverse" square root condition: i * i <= n
(Optionally) Exclude negative numbers
Example implementation:
static boolean isPrime(int x) {
int n = Math.abs(x); // exclude negatives
if (n < 2) return false; // exclude 0, 1
if (n % 2 == 0) return n == 2; // exclude even except 2
for (int i = 3; i * i <= n; i += 2) { // check only odd numbers
if (n % i == 0) {
return false;
}
}
return true;
}
Faster implementation using 6n ± 1 rule (thanks Roberto Caboni) could look like this (starting from 5 (6n - 1) and using variable steps 2 and 4):
static boolean isPrimeFaster(int x) {
int n = Math.abs(x);
if (n < 2) return false; // exclude 0, 1
if (n % 2 == 0) return n == 2; // exclude even except 2
if (n % 3 == 0) return n == 3; // exclude multiples of 3
for (int i = 5, j = 2; i * i <= n; i += j, j = j == 2 ? 4 : 2) {
if (n % i == 0) {
return false;
}
}
return true;
}
You need this implementation
static boolean isPrime(int x)
{
If(x==0||x==1) {
return false;
}
for(int i = 2;i <= x/2;++i)
{
if(x%i == 0)
{
return false;
}
}
return true;
}
The compiler is confused because both return statements are conditional. It isn't sure any one of them will happen. Your program will compile if you simply move the return true; outside the for loop.
class Main
{
static boolean isPrime(int x)
{
for(int i = 2;i <= x/2;++i)
{
if(x%i == 0)
{
return false;
}
}
return true;
}
public static void main (String args[])
{
boolean prime = isPrime(11);
System.out.println(prime);
}
}
Your program will not return a correct answer fo x <= 2. We can fix that by adding a few ifs at the beginning.
class Main
{
static boolean isPrime(int x)
{
if (x < 2)
{
return false;
}
if (x == 2)
{
return true;
}
for(int i = 2;i <= x/2;++i)
{
if(x%i == 0)
{
return false;
}
}
return true;
}
public static void main (String args[])
{
boolean prime = isPrime(11);
System.out.println(prime);
}
}
You can improve the performance of your program without too much of a change by limiting your search to sqrt(x) instead of x/2. And now that we are optimising, we might as well only check the odd numbers.
class Main
{
static boolean isPrime(int x)
{
if (x < 2)
{
return false;
}
if (x == 2)
{
return true;
}
if (x % 2 == 0)
{
return false;
}
int limit = (int) Math.sqrt(x);
for(int i = 3; i <= limit; i += 2)
{
if(x%i == 0)
{
return false;
}
}
return true;
}
public static void main (String args[])
{
boolean prime = isPrime(11);
System.out.println(prime);
}
}
Use a boolean variable and set it true when the number is divisible. Also check if the number is less than 2 because one and zero are not primes so return false then.
The problem in your code currently is that you immediately return false or true after the first iteration but you have to check as long as you found a divisor or you run up from 2 until the square root of x This is more accurate to run until the iterator is less or equal than the square root of the prime
If you are interested why to use the square root as running condition check out this answer
Why do we check up to the square root of a prime number to determine if it is prime?
public static void main(String[] args) {
System.out.println(isPrime(0));
System.out.println(isPrime(3));
System.out.println(isPrime(4));
System.out.println(isPrime(5));
System.out.println(isPrime(11));
}
public static boolean isPrime(int x) {
boolean isPrime = true;;
if(x < 2) {
return false;
}
for(int i = 2; i <= Math.sqrt(x); i++) {
if (x % i == 0) {
isPrime = false;
break;
}
}
return isPrime;
}
Generates the output
false
true
false
true
true
java compiler expects isPrime() always returns a boolean.
you can loop and when remaining become 0 return false. and after and loop return true.
static boolean isPrime(int x)
{
for(int i = 2;i <= x/2;++i)
if(x%i == 0)
return false;
return true;
}
class PrimeNumber
{
static boolean isPrime(int x)
{
boolean status = false;
for(int i = 2;i <= x/2;++i)
{
if(x%i == 0)
{
status = false;
}
else
{
status = true;
}
}
return status;
}
public static void main (String args[])
{
boolean prime = isPrime(11);
System.out.println(prime);
}
}
this will solve your problem

Displaying Palindromic Prime number

I am trying to make a program to display the first 50 prime palindromes with 10 numbers per line. This is the code i have so far, however when run nothing happens. I have looked t similar solutions and can't seem to find were the error is. Any help would be appreciated.
import java.lang.Math;
public class PalindromicPrime {
public static void main(String[] args) {
int counter = 1;
int start = 2;
isPalindrome(start);
isPrime(start);
while (counter <= 50) {
if (isPrime(start) && isPalindrome(start)) {
System.out.print(start + " ");
if (counter % 10 == 0) {
System.out.println();
counter++;
}
start++;
}
}
}
public static boolean isPalindrome(int x) {
int reverse = 0;
while(x > 0) {
reverse = reverse * 10 + x % 10;
x = x / 10;
}
if (reverse == x) {
return true;
}
else {
return false;
}
}
public static boolean isPrime(int x) {
if (x % 2 == 0 && x != 2) {
return false;
}
int sqr = (int)Math.sqrt(x);
for (int i = 3; i <= sqr; i += 2) {
if(x % i == 0) {
return false;
}
}
return true;
}
}
You're not incrementing start when it isn't prime, so you hit an infinite loop when you hit your first non-prime number. Put your start++ outside of the if statement.
Your isPalindrome() method is broken. The variable x is whittled down to create reverse, but then you compare reverse to the modified version of x instead of its original value.
You're only incrementing counter every 10th prime, so this will end up printing 500 palindromic primes, not 50.
Bonus: Finding primes is faster if you store every prime that you find, and then only check division by previously-found primes.
First of all as others have said your isPalindrome() Method is not working correctly.
I would suggest you just convert your int to a string and then check whether that is a Palindrome. I think it is the easiest way. Maybe others can comment whether that is a bad idea in terms of performance.
Here is how I would do it:
public static boolean isPalin(int x) {
String s = Integer.toString(x);
for(int i = 0; i < s.length()/2; i++) {
if(s.charAt(i) != s.charAt(s.length()-i-1)) {
return false;
}
}
return true;
}
Also your while loop is not working correctly as you only increment start when you actually found a prime. Counter should be incremented everytime you found a prime.
On top of that you should base the condition for the while loop on your start value and not the counter for the line breaks.
Edit: Actually you should use counter in the while condition. I was wrong.
Here is the updated code:
public static void main(String[] args) {
int counter = 0;
int start = 2;
while (counter < 50) {
if (isPrime(start) && isPalin(start)) {
System.out.print(start + " ");
counter++;
if (counter % 10 == 0) {
System.out.println();
}
}
start++;
}
}
public static boolean isPalin(int x) {
String s = Integer.toString(x);
for(int i = 0; i < s.length()/2; i++) {
if(s.charAt(i) != s.charAt(s.length()-i-1)) {
return false;
}
}
return true;
}
public static boolean isPrime(int x) {
if (x % 2 == 0 && x != 2) {
return false;
}
int sqr = (int)Math.sqrt(x);
for (int i = 3; i <= sqr; i += 2) {
if(x % i == 0) {
return false;
}
}
return true;
}
Here is the output for the first 50 primes that are palindromic:
2 3 5 7 11 101 131 151 181 191
313 353 373 383 727 757 787 797 919 929
10301 10501 10601 11311 11411 12421 12721 12821 13331 13831
13931 14341 14741 15451 15551 16061 16361 16561 16661 17471
17971 18181 18481 19391 19891 19991 30103 30203 30403 30703
Your code is an Infinite looping. This is because you increment start in the if statement, so only when start is a prime and palindrome number.
If start isn't palindrome or prime, it will not enter the conditional and thus counter will Nevers incréée and reach 50

Do I need a single loop or a nested loop for this?

Let's say I have an array and a boolean method. This boolean method will return true if all the positive numbers appear before all the non-positive numbers (0 inclusive). Otherwise, it will return a false value.
The first array newArrayTrue will return a true value because all the positive numbers appear before all the non-positive numbers and 0. Whereas in newArrayFalse, it will return a false value because 0 appear before 5, and 5 is a positive number.
int[] newArrayTrue = {3,1,-4,0,-5};
int[] newArrayFalse = {3,1,-4,0,5};
public static boolean isPositiveFirst(int[] numbers) {
for (int i=0; i<numbers.length; i++) {
for (int j=i+1; i<numbers.length; i++) {
if (numbers[i] > 0 && (numbers[i+1] < 0 || numbers[i+1] == 0)) {
return true;
}
}
}
return false;
}
}
Do I need to have a nested for loop inside the boolean method or it can be done in just one for loop? And I need help with my conditions as I don't really get what's the issue with it. Appreciate any help.
This should suffice:
public static boolean isPositiveFirst(int[] numbers) {
for(int i = 1; i < numbers.length; i++) {
if(numbers[i] > 0 && numbers[i-1] <= 0) {
return false;
}
}
return true;
}
Also some credit to #Ryan, since he deleted his answer on which I based my code.
You can just use a boolean variable encounteredNegative and set it to true if you encounter a 0 or a negative number. Then continue the iteration and if a positive number is found the method should return false. If the loop ends the method returns true.
Something like this:
public static boolean isPositiveFirst(int[] numbers) {
boolean encounteredNegative = false;
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] <= 0) {
encounteredNegative = true;
} else {
if (encounteredNegative) {
return false;
}
}
}
return true;
}
How about this.
private static boolean areAllPositiveFirst(int[] a)
{
boolean f=false,ans=true;
for (int i = 0; i < a.length; i++)
{
if(f && a[i]>0)
{
ans=false;
break;
}
if(a[i]<=0)
f=true;
}
return ans;
}
As an alternative to the given answers, using IntStream you can do something like :
public static boolean isPositiveFirst(int[] numbers) {
int k = IntStream.range(0, numbers.length).filter(i -> numbers[i]<1).findFirst().orElse(-1);
if(k < 0)
return true;
else
return IntStream.of(Arrays.copyOfRange(numbers, k, numbers.length)).filter(i-> i>0).count() <1;
}
I see that Lyubomir Papazov already came up with this algorithm. My implementation is just a little more terse:
public static boolean isPositiveFirst(int[] numbers) {
boolean seenNonPositive = false;
for(int i : numbers) {
if(i < 1) seenNonPositive = true;
else if(seenNonPositive) return false;
}
return true;
}

Finding prime numbers with a custom IsPrime method

I started learning Java about one month ago and today I saw this question I couldn't solve.
The question was:
Write a method named isPrime, which takes an integer as an argument and returns true
if the argument is a prime number, or false otherwise. Demonstrate the method in a complete program.
And the second part says:
Use the isPrime method that you wrote in previous program in a program that
stores a list of all the prime numbers from 1 through 100 in a file.
Here's my code, which doesn't work:
import java.io.*;
public class PrimeNumbers {
public static void main (String args[]) throws IOException {
PrintWriter outputFile = new PrintWriter("PrimeNumber.txt");
int j = 0;
for (int i = 0; i < 100; i++) {
isPrime(i);
outputFile.println("Prime nums are:" + i);
}
}
public static boolean isPrime (int j) {
int i;
for (j = 2; j < i; j++) {
if (i % j == 0) {
return false;
}
if (i == j) {
return true;
}
}
}
}
Your condition for returning true in isPrime - if (i == j) - can never be met, since it's inside a loop whose condition is j < i. Instead, just return true after the loop. If the loop ends without returning false, you know for sure that the input number is prime.
Your code that uses isPrime is not checking the value returned by this method. You must check it in order to decide whether to write the number to the output file.
import java.io.IOException;
import java.io.PrintWriter;
public class PrimeNumbers
{
public static void main(String args[]) throws IOException
{
PrintWriter primeNumbersWriter = new PrintWriter("PrimeNumber.txt");
for (int i = 0; i < 100; i++)
{
// You didn't do anything with the return value of isPrime()
if (isPrime(i))
{
primeNumbersWriter.println("Prime numbers are: " + i);
}
}
// Please close writers after using them
primeNumbersWriter.close();
}
public static boolean isPrime(int prime)
{
// Do not use the number to check for prime as loop variable, also it's
// sufficient to iterate till the square root of the number to check
for (int number = 2; number < Math.sqrt(prime); number++)
{
if (prime % number == 0)
{
return false;
}
}
// You didn't always return a value, it won't let you compile otherwise
return true;
}
}
Prime Number A prime number (or a prime) is a natural number greater
than 1 that has no positive divisors other than 1 and itself.
What should be the logic?
Pass a number to method.
Use loop to start a check of modulo % to find at least one number which can divide the passed number.
Check until we reached the value passedNumber.
If the modulo gives 0 for atleast one, it's not prime thank god!
If modulo is not 0 for any number ...oh man it's Prime.
What are the problems in your code?
You are looping correctly but using the variable j which is the limit and you are incrementing it!
If you want to loop through i < j how can the condition i == j be true?
If method is returning boolean why are you using method as void! Use that returned value.
You can just return false at the end if divisor not found!
We did it...Just try now!
about isPrime: First of all, u should loop for( j = 2; j*j <= i; j++)
the reason for this loop is that if a number isn't prime, its factor must be less or equal to the squared root of i, so there is no need to loop after that point
now, if loop didn't return false - return true`
about second function: use if before checking isPrime - if(isPrime(i)) {add i to list}
see here is your solution.
import java.util.Scanner;
public class Testing {
public static void main(String args[]) {
Scanner scnr = new Scanner(System.in);
int number = Integer.MAX_VALUE;
System.out.println("Enter number to check if prime or not ");
while (number != 0) {
number = scnr.nextInt();
System.out.printf("Does %d is prime? %s %s %s %n", number,
isPrime(number), isPrimeOrNot(number), isPrimeNumber(number));
}
}
/*
* Java method to check if an integer number is prime or not.
* #return true if number is prime, else false
*/
public static boolean isPrime(int number) {
int sqrt = (int) Math.sqrt(number) + 1;
for (int i = 2; i < sqrt; i++) {
if (number % i == 0) {
// number is perfectly divisible - no prime
return false;
}
}
return true;
}
/*
* Second version of isPrimeNumber method, with improvement like not
* checking for division by even number, if its not divisible by 2.
*/
public static boolean isPrimeNumber(int number) {
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;
}
/*
* Third way to check if a number is prime or not.
*/
public static String isPrimeOrNot(int num) {
if (num < 0) {
return "not valid";
}
if (num == 0 || num == 1) {
return "not prime";
}
if (num == 2 || num == 3) {
return "prime number";
}
if ((num * num - 1) % 24 == 0) {
return "prime";
} else {
return "not prime";
}
}
}

I can't figure out my error in my PrimeGenerator

In the output, I get a 9 where I should be getting an 11!
This occurs after the fifth call to nextPrime(). Every other output is correct except for the 5th one! I have been struggling to determine my error for a few hours now. Sorry if my code is sloppy, this is the way my mind figured out the problem! It was a requirement to use the flag controlled loop.
public class PrimeGenerator
{
private int num = 2;
public PrimeGenerator()
{
}
public int nextPrime()
{
boolean done = false;
for (int n = num; !isPrime(num); n++)
num = n;
if (isPrime(num))
{
done = true;
}
if (done)
{
int prime = num;
num++;
return prime;
}
return num;
}
public static boolean isPrime(int n)
{
boolean result = true;
for (int i = 2; n % i == 0 && i < n; i++)
result = false;
if (n == 2)
result = true;
return result;
}
}
My Tester just calls the nextPrime() method and prints the result.
You get 9 instead of 11 because you have mistake in method isPrime
public static boolean isPrime(int n)
{
boolean result = true;
for (int i = 2; n % i == 0 && i < n; i++)
result = false;
if (n == 2)
result = true;
return result;
}
Look for number 9.
first iteration: i = 2, result = true
n % i => 9 % 2 = 1, so your loop stops before first iteration and result didn't changed.
Try to change method isPrime (Updated as commented #John in comments)
public static boolean isPrime(int n)
{
if( n % 2 == 0 ) {
return false;
}
double root = Math.sqrt(n);
for ( int i = 3; i < root; i+=2 ) {
if( n % i == 0 ) {
return false;
}
}
return true;
}
Your nextPrime method returns num whether or not it is prime. Your code is effectively:
if(isPrime(num))
return num;
}
return num;
So the main problem with your code here is the method for checking if a number is prime. According to number theory, you just need to check that the given number is not divisible by any number between 2 and the root of the given number you want to determine is prime. More formally, if you want to check if a number n is prime, you need to check that n is not divisible by any number between 2 and sqrt(n).
An updated method using this number theory fact is below:
public static boolean isPrime(int n)
{
int root = (int)Math.sqrt(n);
for (int i = 2; i <= root; i++) {
if(n % i == 0) {
return false;
}
}
return true;
}
With this your determination of the prime number would be correct and would be much faster. There are even faster ways of determining primes and generating primes like sieve's algorithm.

Categories