For my Java class, we have to write a program that displays all palindromic primes based on a number the user inputs. There are a couple other questions like this, but I need to do it without creating an array, or just typing in all of the palindromic primes.
My program works, and displays all primes, but the problem is that it displays ALL primes, not just the palindromic ones. I don't know where the error is, but I would appreciate any help I can get!
Thanks,
Ben
import java.util.Scanner;
public class PalindromePrimes {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int startingPoint = 1;
int startingPrime = 2;
final int printPerLine = 10;
IsItPrime(startingPrime);
IsItPalin(startingPrime);
System.out.println("Please Enter a Number: ");
int n = in.nextInt();
while (startingPoint <= n)
{
if (IsItPrime(startingPrime) && IsItPalin(startingPrime)) {
System.out.print(startingPrime + " ");
if (startingPoint % printPerLine == 0)
System.out.println();
startingPoint++;
}
startingPrime++;
}
}
public static boolean IsItPrime(int sPrime) {
if (sPrime == 2) {
return true;
}
for(int i = 2; 2 * i < sPrime; i++) {
if(sPrime % i == 0){
return false;
}
}
return true;
}
public static boolean IsItPalin(int sPrime) {
int p;
int reverse = 0;
while (sPrime > 0) {
p = sPrime % 10;
reverse = reverse * 10 + p;
sPrime = sPrime / 10;
}
if (sPrime == reverse) {
return false;
}
return true;
}
}
You could really improve both functions:
Some notes about IsItPrime:
Check first only for even numbers (you are doing this)
The for-loop could begin in 3 and increment by 2, to check only odd numbers, the even are checked in the previous point.
The for-loop only needs to check from 3 .. sqrt(N) + 1, if the number is not prime. It would be a prime if the number is less or equal to sqrt(N) and devides N.
Function IsItPrime improve:
public static boolean IsItPrime(int sPrime) {
if (sPrime % 2 == 0 && sPrime != 2) {
return false;
}
int sqrtPrime = (int)Math.sqrt(sPrime);
for (int i = 3; i <= sqrtPrime; i += 2) {
if (sPrime % i == 0) {
return false;
}
}
return true;
}
Some notes about IsItPalin:
The return result is swapped, when sPrime == reverse is palindrome, you must return true, not false.
The other problem is that in the function you are modifying the parameter sPrime in the while-loop, you need to save the original value for comparing in sPrime == reverse.
Function IsItPalin improved:
public static boolean IsItPalin(int sPrime) {
int sPrimeBackup = sPrime;
int reverse = 0;
while (sPrime > 0) {
reverse = reverse * 10 + sPrime % 10;
sPrime = sPrime / 10;
}
return (sPrimeBackup == reverse);
}
The problem is in the IsItPalin method. You are changing the value of sPrime, but then comparing sPrime to reverse. Make a copy of sPrime and compare the copy to reverse. Also, you should return true if they are equal, not false.
It looks like the problem is with your IsItPalin method. It's almost right, except for two problems.
The first problem is this:
if (sPrime == reverse) {
return false;
}
return true;
Whenever your prime number is equal to the reverse, you're returning false! This is the opposite of what we want.
The fix is to switch "true" and "false":
if (sPrime == reverse) {
return true;
}
return false;
We can actually simplify this into a single line:
return sPrime == reverse;
The second problem is with sPrime. Within your while loop, you're decreasing sPrime, and will only exit the loop when sPrime is equal to zero. That means that the only time sPrime will be equal to reverse is when you input the value of 0. To fix this, make a copy of sPrime at the top of the method and compare the copy to reverse.
The fixed version would look like this:
public static boolean IsItPalin(int sPrime) {
int copy = sPrime;
int reverse = 0;
while (sPrime > 0) {
int p = sPrime % 10;
reverse = reverse * 10 + p;
sPrime = sPrime / 10;
}
return copy == reverse;
}
This solution doesn't involve a loop, so it's probably faster
public static boolean isPaladrome(int mNumber) {
String numToString = String.valueOf(mNumber);
int sLength = numToString.length();
int midPoint = sLength / 2;
return (new StringBuilder(numToString.substring(0, midPoint)).reverse()
.toString()).equals(numToString.substring(sLength - midPoint));
}
Related
I have to write a program that returns Fibonacci number, but not only positive. I don't know what is not right in the way I've wrote it, but my code works with positive numbers and not with negative ones.
public static int negFib(int n) {
if(n==0 || n==1) {
return n;
}
if(n==-1) {
return 1;
}
if(n<0 && n%2==0) {
//return negFib(n+2) - negFib(n+1);
return (-1<<(n+1))*(negFib(n-1) + negFib(n-2); // Fibonacci negative
//F(n)=F(n+2)−F(n+1)
//F(−1)=F(1)−F(0)=1−0=1 , F(−2)=F(0)−F(1)=0−1=−1
}
return negFib(n-1) + negFib(n-2); //Fibonacci positive
}
Well, if you want to use the F−n = (−1)n+1Fn formula:
public static int negFib(int n) {
if(n==0 || n==1) {
return n;
}
if(n==-1) {
return 1;
}
if(n<0) {
int sign = n % 2 == 0 ? -1 : 1;
return sign * negFib(-n);
} else {
return negFib(n-1) + negFib(n-2);
}
}
Your attempt had several issues:
for negative n (either odd or even), you should make the recursive call for -n-1 and -n-2.
your calculation of the sign - (-1<<(n+1)) - is wrong.
Try this :
long f[] = new long[(int) (n+2)];
long i;
f[0]=0;
f[1]=1;
for (i=2; i <= n; i++) {
f[(int) i] = f[(int) (i-1)] + f[(int) (i-2)];
}
I am trying to write a function in Java that returns the greatest digit in a number using recursion.
I have managed to do it using two parameters, the number and greater digit.
Initially the greater digit parameter accepts value as 0.
static int getGreatestDigit(int num , int greater){
if(num != 0){
if(num %10 > greater){
greater = num%10;
num = num/10;
return getGreatestDigit(num , greater);
}else{
num = num/10;
return getGreatestDigit(num , greater);
}
}
return greater;
}
I want to write same recursive function but with only one parameter that is number.
Like
int getGreatestDigit(int num){
//code
}
I am stuck at logic. How to do that?
Only the first call to getGreatestDigit(num) needs to keep track of the greater result. Each recursive call to getGreatestDigit(num) will return the greatest digit in the part of the original number that it is tasked with scanning. The very first invocation of getGreatestDigit(num) can compare the number it took with the greatest number returned from all recursive calls.
int getGreatestDigit(int num)
{
if (num == 0) return 0;
int lastNum = num % 10;
int otherDigits = num / 10;
int recursiveLastNum = getGreatestDigit(otherDigits);
return Math.Max(lastNum, recursiveLastNum);
}
static int getGreatestDigit(int num)
{
return num == 0 ? 0 :
Math.Max(num % 10, getGreatestDigit(num / 10));
}
So basically, you look at the least significant digit each time, comparing it against the maximum of the rest of the digits.
You can do this, if you use the functions stack as temporary memory to hold your interim results, i.e. what was previously stored in the greater parameter.
This changes your function to be no longer tail recursive, making it worse performance wise.
int greatestDigit(int num) {
int last = num % 10;
int rest = num / 10;
if (rest == 0) {
return last;
} else {
int candidate = greatestDigit (rest);
if (candidate > last) {
return candidate;
} else {
return last;
}
}
}
/** Pseudocode:
1. if num > 9, /10 and call getGreatestDigit on that (recursive step). Then get the current digit (undivided) and return the greater of the two
2. if num <= 9, return num
*/
int getGreatestDigit(int num){
//code
}
package Map;
import java.util.ArrayList;
public class Practice8 {
public int highestDigit(int number){
ArrayList<Integer> temp= new ArrayList<>();
StringBuilder sb= new StringBuilder();
sb.append(number);
String value= sb.toString();
for(int i=0;i<value.length();i++){
temp.add((int)value.charAt(i)-'0');
}
int max=0;
for(int x: temp){
if(x>max){
max=x;
}
}
return max;
}
public static void main(String[] args) {
Practice8 practice8= new Practice8();
System.out.println(practice8.highestDigit(379));
}
}
I have been trying this for some time now but could not get it to work. I am trying to have a method to reverse an integer without the use of strings or arrays. For example, 123 should reverse to 321 in integer form.
My first attempt:
/** reverses digits of integer using recursion */
public int RevDigs(int input)
{
int reverse = 0;
if(input == 0)
{
return reverse;
}
int tempRev = RevDigs(input/10);
if(tempRev >= 10)
reverse = input%10 * (int)Math.pow(tempRev/10, 2) + tempRev;
if(tempRev <10 && tempRev >0)
reverse = input%10*10 + tempRev;
if(tempRev == 0)
reverse = input%10;
return reverse;
}//======================
I also tried to use this, but it seems to mess up middle digits:
/** reverses digits of integer using recursion */
public int RevDigs(int input)
{
int reverse = 0;
if(input == 0)
{
return reverse;
}
if(RevDigs(input/10) == 0)
reverse = input % 10;
else
{
if(RevDigs(input/10) < 10)
reverse = (input % 10) *10 + RevDigs(input/10);
else
reverse = (input % 10)* 10 * (RevDigs(input/10)/10 + 1) + RevDigs(input/10);
}
return reverse;
}
I have tried looking at some examples on the site, however I could not get them to work properly. To further clarify, I cannot use a String, or array for this project, and must use recursion. Could someone please help me to fix the problem. Thank you.
How about using two methods
public static long reverse(long n) {
return reverse(n, 0);
}
private static long reverse(long n, long m) {
return n == 0 ? m : reverse(n / 10, m * 10 + n % 10);
}
public static void main(String... ignored) {
System.out.println(reverse(123456789));
}
prints
987654321
What about:
public int RevDigs(int input) {
if(input < 10) {
return input;
}
else {
return (input % 10) * (int) Math.pow(10, (int) Math.log10(input)) + RevDigs(input/10);
/* here we:
- take last digit of input
- multiply by an adequate power of ten
(to set this digit in a "right place" of result)
- add input without last digit, reversed
*/
}
}
This assumes input >= 0, of course.
The key to using recursion is to notice that the problem you're trying to solve contains a smaller instance of the same problem. Here, if you're trying to reverse the number 13579, you might notice that you can make it a smaller problem by reversing 3579 (the same problem but smaller), multiplying the result by 10, and adding 1 (the digit you took off). Or you could reverse the number 1357 (recursively), giving 7531, then add 9 * (some power of 10) to the result. The first tricky thing is that you have to know when to stop (when you have a 1-digit number). The second thing is that for this problem, you'll have to figure out how many digits the number is so that you can get the power of 10 right. You could use Math.log10, or you could use a loop where you start with 1 and multiply by 10 until it's greater than your number.
package Test;
public class Recursive {
int i=1;
int multiple=10;
int reqnum=0;
public int recur(int no){
int reminder, revno;
if (no/10==0) {reqnum=no;
System.out.println(" reqnum "+reqnum);
return reqnum;}
reminder=no%10;
//multiple =multiple * 10;
System.out.println(i+" i multiple "+multiple+" Reminder "+reminder+" no "+no+" reqnum "+reqnum);
i++;
no=recur(no/10);
reqnum=reqnum+(reminder*multiple);
multiple =multiple * 10;
System.out.println(i+" i multiple "+multiple+" Reminder "+reminder+" no "+no+" reqnum "+reqnum);
return reqnum;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int num=123456789;
Recursive r= new Recursive();
System.out.println(r.recur(num));
}
}
Try this:
import java.io.*;
public class ReversalOfNumber {
public static int sum =0;
public static void main(String args []) throws IOException
{
System.out.println("Enter a number to get Reverse & Press Enter Button");
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String input = reader.readLine();
int number = Integer.parseInt(input);
int revNumber = reverse(number);
System.out.println("Reverse of "+number+" is: "+revNumber);
}
public static int reverse(int n)
{
int unit;
if (n>0)
{
unit = n % 10;
sum= (sum*10)+unit;
n=n/10;
reverse(n);
}
return sum;
}
}
See, I have a boolean method that gets the divisors that work by moding the number by a divisor that is checked and determined true by a for loop (not the first one, that just loops the program for a determined amount of input.
I'm not sure if there's some way to take the multiple results of the loop and add them together, but that is what I need to do. right now I'm displaying the results of the loop but that was for debugging, in the end the output will be whether it is abundant (the added divisors are over the number), perfect (the added divisors equal the number) or deficient (the added divisors are less then the number)
This is the code in eclipse:
import java.util.*;
public class PerfectNumber {
/**
* #param args
*/
public static void main(String[] args) {
for(int i = 0; i < 15; i++)
{
Scanner reader = new Scanner(System.in);
int number = 0;
int divisor = 1;
int addnum = 0;
System.out.println("Please input a number to check if it is perfect, abundant, or deficient");
number = reader.nextInt();
for(divisor = 1; divisor < number; divisor++)
{
isDivisor(number, divisor);
if(isDivisor(number, divisor) == true)
{
System.out.println(divisor);
}
}
}
}
static boolean isDivisor(int number, int divisor)
{
if (number % divisor == 0)
return true;
else
return false;
}
}
To answer what seems to be your immediate question for what smells like a homework problem ;)
I'm not sure if there's some way to take the multiple results of the loop and add them together
You can check the return of your function as you're already doing and increment a counter
public boolean isSeven(int x){
return x == 7;
}
public static void main(String[] args){
int sumOfSevens= 0;
int i = 0;
while(i < 10){
if(isSeven(7)){
sumOfSevens = sumOfSevens + 7; // or +=
++i;
}
}
// At this point sumOfSevens = 70;
}
You don't need isDivisor because it is equal to the following expression:
number % divisor == 0
Just sum up divisors:
int numDivSum = 0;
for(divisor = 1; divisor < Math.sqrt(number); divisor++)
{
if(number % divisor == 0)
{
numDivSum += divisor;
}
}
and check is the numDivSum is perfect, abundant, or deficient.
If you want to sum things in a loop you can use some statement like this:
Int sum;
// your for loop start
If ( isDivisor(number, divisor))
sum += divisor;
// end of loop
//here you can do the comparison.
There is no need to compare to true in your if-statement. Also this codesnippet only works, if you have only one statement in the if body. If you need to do multiple things, you have to wrap that whole thing in brackets.
Also your first call to isDivisor is useless, as you are not doing anything with the value you get.
is there a more efficient, cleaner/elegant way of finding prime numbers than this? The code works fine, but I just wrote what seemed most logical to me and I can't figure out any other way, but to be honest it just doesn't look nice :P. I know coding isn't the most elegant of activities.
Here's my main method:
import java.util.Scanner;
public class DisplayPrimeNumbers
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.print("Enter an integer that you'd like the system to print the prime numbers till: ");
String input1 = scan.nextLine();
int input = Integer.parseInt(input1);
PrimeGenerator prime = new PrimeGenerator(input);
for (int i = 1; i < input ; i++)
{
if(prime.isPrime())
{
System.out.println(prime.getNextPrime());
}
}
System.out.println(1);
}
}
Here's my class:
public class PrimeGenerator
{
private int number;
public PrimeGenerator(int n)
{
number = n;
}
public int getNextPrime ()
{
return number+1;
}
public boolean isPrime()
{
for(int i = 2; i < number; i++)
{
if (number % i == 0)
{
number--;
return false;
}
}
number--;
return true;
}
}
While this question has already been answered I figured I'd provide my answer anyway in the hopes that somebody may find it useful:
You seem to be primarily concerned with 2 both elegance and efficiency. I'd also like to point out that correctness is equally important. Unless you have a special requirement to treat the number 1 as prime it is no longer considered so. You should equally consider the scenario when the user enters a prime number. You should also give some thought into the boundry condition of what numbers you print. Specifically if I enter the number 7, will your users expect it to output 5,3,2,1 or 7,5,3,2,1. While my personal tendency would be towards the latter, using clear and concise messages can make either option work.
Elegance
The perceived lack of elegance in your solution is largely due to your combination of two concepts: Prime Number Testing and Prime Number Generation.
A Prime Number Test is a (quick) method to determine whether or not a single arbitrarily chosen number is prime.
A Prime Number Generator is a way of generating a sequence of prime numbers which are often consecutive.
As your program demonstrates you can generate a consecutive sequence of prime numbers by testing each number within a given range and only selecting those which are prime! Keeping this as our basic strategy for the moment, let's figure out what the code might:
From our description earlier we said that a prime number test was a method (aka function) to determine if some arbitrarily chosen number was prime. So this method should take as input a(n arbitrarily chosen) number and return wether or not the given numbe was prime (ie: true/false). Let's see how it looks:
public interface PrimeNumberTest
{
bool isPrime(int value);
}
And incorporating your prime number test
public class BruteForcePrimeNumberTester : PrimeNumberTest
{
public bool isPrime(int value)
{
bool isPrime = true;
for(int i = 2; isPrime && i < value; i++)
{
if (value % i == 0)
{
isPrime = false;
}
}
return isPrime;
}
}
Your main program is then responsible for iterating over each number and printing only thsoe which the prime number test identifies as prime.
public static void main(String[] args)
{
//Determine the range of prime numbers to print
Scanner scan = new Scanner(System.in);
System.out.print("Primes smaller than what number should be printed?: ");
int max = Integer.parseInt(scan.nextLine());
//Identify how prime numbers will be tested
PrimeNumberTest test = new BruteForcePrimeNumberTest();
//Uncomment the line below if you want to include the number 1. Favour adding it here so that you may
//use re-use your prime number test elsewhere that atually needs to know if a number is prime.
//System.out.println(1);
//Print the prime numbers
for (int i = 2; i < max ; i++)
{
if(test.isPrime(i))
{
System.out.println(i);
}
}
}
Your main program however should only be concerned with prime number generation. It doesn't really care about the semantics of how those primes are generated we just want the primes. It doesn't really matter if the primes were found via primality testing or any other algorithm. So we ask ourselves what does a prime number generator look like?
For starter primes are always whole numbers so we shouldn't be storing them inside floats, doubles or decimals. That leaves 32 and 64 bit integers. If you want to generate larger prime numbers then obviously you should use the long type but I'm just going to use int. In other languages we would also have to consider things like unsigned numbers too.
Now we need to find a way to return all of these numbers at once. Trees don't really make sense as we're going to be generating a consecutive sequence. Stacks don't make sense because consumers typically want the numbers in the order they were generated. Queues could be used as they fit the first-in-first-out rule. In fact if the end application had an asynchronous prime number generator (producer) and a separate asynchronous consumer this type would be ideal. For this example however I want something read-only. Essentially a prime number generator is an Iterable<int>.
public class PrimeNumberTestGenerator : Iterable<int>
{
private int limit;
private PrimalityTester tester;
public PrimeNumberTestGenerator(PrimalityTester tester, int limit)
{
this.tester = tester;
this.limit = limit;
}
private class PrimeNumberIterator : Iterator<int>
{
private int current;
public PrimeNumberIterator()
{
}
public bool hasNext()
{
return next < limit;
}
public int moveNext()
{
if (!hasNext())
{
throw new NoSuchElementException();
}
int result = next;
do
{
next++;
} while(hasNext() && !tester.isPrime(next));
return result;
}
public void remove()
{
throw new UnsupportedOperationExecution();
}
}
public Iterator<int> iterator()
{
return new PrimeNumberIterator();
}
}
So how do we tie them together?
public static void main(String[] args)
{
//Determine the range of prime numbers to print
Scanner scan = new Scanner(System.in);
System.out.print("Primes smaller than what number should be printed?: ");
int max = Integer.parseInt(scan.nextLine());
//Identify how prime numbers will be tested
Iterable<int> primes = new PrimeNumberTestGenerator(max, new BruteForcePrimeNumberTest());
//Print the prime numbers
foreach (int prime : primes)
{
System.out.println(prime);
}
}
Efficiency
Now the other side of your question was an efficient way of determining the prime numbers within a specified range. While a quick internet search should yield a number of different "fast" algorithms for determing a set of prime numbers that are much faste than the brute force way. One such approach is the Sieve of Atkin:
public class AtkinSieve : Iterable<int>
{
private BitSet primes;
public AtkinSieve(int limit)
{
primes = new BitSet(limit);
int root = (int)Math.sqrt(limit);
primes.set(2);
primes.set(3);
//this section can be further optimized but is the approach used by most samples
for (int x = 1; x <= root; x++)
{
for (int y = 1; y <= root; y++)
{
int number;
int remainder;
number = (4 * x * x) + (y * y);
remainder = number % 12;
if (number < limit && (remainder == 1 || remainder == 5))
{
primes.flip(number);
}
number = (3 * x * x) + (y * y);
remainder = number % 12;
if (number < limit && remainder == 7)
{
primes.flip(number);
}
if (x < y)
{
number = (3 * x * x) - (y * y);
remainder = number % 12;
if (number < limit && remainder == 11)
{
primes.flip(number);
}
}
}
}
for (int i = 5; i <= root; i++)
{
if (primes.get(i))
{
int square = i * i;
for (int j = square; j < limit; j += square)
{
primes.clear(j);
}
}
}
}
}
public class SetBitIterator : Iterator<int>
{
private BitSet bits;
private int next;
private bool isReadOnly;
public SetBitIterator(BitSet bits)
{
this.bits = bits;
next = bits.nextSetBit(0);
}
public bool hasNext()
{
return next <> -1;
}
public int moveNext()
{
int result = next;
next = bits.nextSetBit(next);
return result;
}
public void remove()
{
throw new UnsupportedOperationException();
}
}
Conveniently we can now use this prime number generator by only changing a single line in our previous main program!
Change:
//Identify how prime numbers will be tested
Iterable<int> primes = new PrimeNumberTestGenerator(max, new BruteForcePrimeNumberTest());
To:
//Identify how prime numbers will be tested
Iterable<int> primes = new AtkinSieve(max);
You can speed up your search for new primes by storing the primes that you have already found in a private collection inside the PrimeGenerator. By trying only them as potential divisors instead of your for(int i = 2; i < number; i++) loop, you will have to do much fewer divisions
You can stop the "find divisors" loop well before you reach the number: specifically, you can stop when your candidate divisor exceeds the square root of the target number. This works, because you try the candidate divisors in ascending order: if there were divisors above the square root, the result of the division would have been below the square root, so you would have already found them.
Your getNextPrime method should call isPrime internally before returning the value to the caller. Otherwise, the call of getNextPrime cannot be said to return the next prime.
First and most important thing is.... U need not to check till
i
for(int i = 2; i < number; i++)
U need to to check only untill i is less than number/2...
for(int i = 2; i < (number/2); i++)
This is how I might have written it for simplicity
public static void main(String... args) {
System.out.print("Enter an integer that you'd like the system to print the prime numbers till: ");
Scanner scan = new Scanner(System.in);
int input = scan.nextInt();
if (input >= 2)
System.out.println(2);
OUTER: for (int i = 3; i <= input; i += 2) { // skip every even number
for (int j = 3; j * j <= i; j += 2) // stop when j <= sqrt(i)
if (i % j == 0)
continue OUTER;
System.out.println(i); // 99+% of the time will be spent here. ;)
}
}
Yeah there are. I don´t know if it´s the most efficient, but it is way more efficient then this one. Check the Miller Rabin test.
Even so, if you want to work with your Code, i could tell you, you should do it like this:
public boolean isPrime(int number)
{
// You should know, that every straight number can not be prime,so you can say i+= 2
if (number == 2)
return true;
if (number % 2 == 0)
{
return false;
}
for(int i = 3; i < number; i+=2)
{
if (number % i == 0)
{
number--;
return false;
}
--number;
return true;
}
Why would a PrimeGenerator produce numbers that are not prime? That's not elegant. Remove the isPrime()-method and rewrite the getNextPrime()-method so that it will always return a prime number.
As an improvement you can step by 6 not by 2 and do 2 checks in each step. See what I found here.
Basically, every number can be written as (6k, 6k + 1, 6k+2, 6k+3,
6k+4, or 6k+5). 6k is clearly not prime. Items 6k+2 to 6k+4 can be
written as 2(3k + 1), 3(2k+1), and 2(3k + 2) and therefore aren’t
prime as they’re divisible by 2 or 3.
So my point is the following. If we want to find numbers up to 1000 we can do the following thing.
int [] primes = new int[1000];
primes[0] = 2;
primes[1] = 3;
primes[2] = 5;
primes[3] = 7;
index = 4;
for(int i = 12; i < 1000; i += 6) {
boolean prime1 = true;
boolean prime2 = true;
int j = 1; // No need to divide by 2, the number is odd.
while(j < index && (prime1 || prime2)) {
if (prime1 && ((i - 1) % primes[j] == 0)) {
prime1 = false;
}
if (prime2 && ((i + 1) % primes[j] == 0)) {
prime2 = false;
}
j++;
}
if (prime1) {
primes[index++] = i - 1;
}
if (prime2) {
primes[index++] = i + 1;
}
}
Try this code mate.I wrote this. This is more elegant i think :)
**import java.util.*;
public class PrimeNum{
public static void main(String args[]){
Scanner x=new Scanner(System.in);
System.out.println("Enter the number : ");
long y=x.nextLong();
long i;
for( i=2;i<y;i++){
long z=y%i;
if(z==0){
System.out.println(y+" is not a prime");
System.out.println(y+" Divide by "+i);
i=y;
}
}if(i==y) System.out.println("Number is prime");
if(y==1) System.out.println("Number 1 is not a prime");
}
}**
Based on my observations a basic approach would be to use this:
int prime(int up_limit){
int counter =0;
for(int i=1;i<=up_limit;i++)
{
if(up_limit%i==0)
counter++;
}
if(count==2){
return up_limit;
}