Im having trouble in the reverse order section of my code. I'm storing the values in hund, tens, ones, etc. How do I pass the data back to the main method so as to display these numbers in reverse order?
import java.util.Scanner;
public class PP53v2 {
public static void main(String[] args) {
int leftOver = 0;
int number = 0;
int num1;
Scanner input = new Scanner(System.in);
System.out.println("Hit #1 to reverse a number. Hit #2 to return if its a palindrome.");
int selection = input.nextInt();
switch(selection) {
//problem 1
case 1:
System.out.println("Enter a number to be displayed in reverse order.");
System.out.println("For accuracy, this must be a five digit number.");
number = input.nextInt();
num1 = reverse(number);
System.out.print(num1);
break;
//problem 2
case 2:
System.out.println("Enter an integer to see if it's a palindrome.");
System.out.println("For accuracy, this must be a five digit number. (I.E. 12321 is a palindrome)");
number = input.nextInt();
if (isPalindrome(number)) {
System.out.println("The number is a palindrome." + number);
} else
System.out.println("The number isn't a palindrome." + number);
break;
}//switch end
}//main end
public static int reverse(int number) {
String leftOver = 0;
int remaining =0;
int tenThou = 0, thou = 0, tens = 0, ones = 0; //no need for hundreds
while (number > 0) {
tenThou = number / 10000;
thou = number % 10000 / 1000;
tens = number % 100 /10;
ones = number % 10;
//remaining = number % 10;
//number = number / 10;
//leftOver = leftOver + remaining;
}//end while
return leftOver;
}// reverse method end
public static boolean isPalindrome(int number) {
int tenThou = 0, thou = 0, tens = 0, ones = 0; //no need for hundreds
tenThou = number / 10000;
thou = number % 10000 / 1000;
tens = number % 100 /10;
ones = number % 10;
if (tenThou == ones && thou == tens)
return true;
else
return false;
}//method end
}//class end
Use this logic
while( n != 0 )
{
reverse = reverse * 10;
reverse = reverse + n%10;
n = n/10;
}
n is the integer(your input).
Related
I'm facing troubles solving the following question: I suppose to get the user to input a number and check if it is a lucky number. A lucky number is the sum of squares of even-positioned digit (starting from the second position) is a multiple of 7.
Following is the example of my codes, when i run the program it will stuck at user input, please advise how do i get it to run:
public class Tester {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Input a number: ");
int number = scanner.nextInt();
int count = 0;
while(number!=0) {
number/=10;
++count;
}
int[] array = new int[count];
int sum = 0;
for (int i=0; i<count; i++) {
array[i] = scanner.nextInt();
}
for (int i=0; i<count; i++) {
if(array[i]%2==0) {
sum+=(array[i]*array[i]);
}
else {
continue;
}
}
if (sum%7==0) {
System.out.println("The number: " +number+ "is a Lucky number");
}
else {
System.out.println("Oops! Not a Lucky number");
}
scanner.close();
}
}
I believe the culprit is the below loop:
for (int i=0; i<count; i++) {
array[i] = scanner.nextInt();
}
I think your intention was to get each of the digits into an array. However, you are getting an input from the scanner (which in this case is the user input) for count number of times.
While there are several ways of getting the number of digits and each digit into an array. I'm going to give you two ways. Also, I see no validations on the input integer (such as negative numbers, etc.) and I am going to ignore them right now.
Approach 1: Your for loop corrected
You just get the ith digit of the number using a formula.
for (int i=1; i<=count; i++) {
array[i] = (int) (number / Math.pow(10, count-i)) % 10;
}
Approach 2: Converting the numbers to String and back using streams
List<Integer> digits = Arrays.toStream(number.toString().split("")).map(
digitChar -> Integer.parseInt(digitChar)
).collect(Collectors.toList());
Note:
You need to import the classes java.util.Arrays and java.util.stream.Collectors
If you want even positioned digits,then you can directly get it in while loop.
while(number!=0) {
if(count%2 !=0){
int value = number %10; // even positioned values
// Do whatever you need to do with this value
}
number/=10;
++count;
}
If you want to convert the number into an digit array,then first find number of digits using log function and then store it array in reverse order.
int noOfDigits =(int) Math.floor(Math.log10(number)+1); // Finding No of digits
int[] array = new int[noOfDigits];
while(--noOfDigits>=0){
array[noOfDigits] = number/10; // storing every digits in reverse order
number%=10;
}
I don't know below code will be helpful for your core logic,yet I record this too.
If you want Sum of Squares of even positioned digits in number which is represented as array, then you can use below code.
int sum = 0;
for (int i=1; i<array.length; i+=2) {
sum += array[i] * array[i];
}
if (sum%7==0) {
// print number is lucky
}
else {
// print number is not lucky
}
If I understand your description correctly, here's a program that does what you want:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Input a number: ");
System.out.flush();
int number = scanner.nextInt();
int count = 0;
int n = number;
int sum = 0;
while(n!=0) {
int d = n % 10;
n/=10;
++count;
if (count % 2 == 0) {
System.out.printf("sum = %d + %d^2 = %d\n", sum, d, sum + d * d);
sum += d * d;
}
}
if (sum%7==0) {
System.out.printf("The number: %d is a Lucky number (%d = 7 * %d)", number, sum, sum / 7);
}
else {
System.out.println("Oops! Not a Lucky number");
}
scanner.close();
}
A lucky result:
Input a number: 123456
sum = 0 + 5^2 = 25
sum = 25 + 3^2 = 34
sum = 34 + 1^2 = 35
The number: 123456 is a Lucky number (35 = 7 * 5)
I have a class assignment where we have to use Math.random to generate values of 0 or 1 representing heads and tails respectively. The point of the program is to have the user input the number of times the coin is flipped, and the program then spits out a string of random 0s and 1s representing the flips. The program then has to find and state the longest number of heads in a row.
eg.
(heads = 0 / tails = 1)
number of tosses: 10
result: 0001100100
longest sequence of heads: 3
this is what I have so far:
import java.util.Scanner;
import java.lang.Math;
public class CoinFlip
{
public static void main(String args[])
{
int Toss; // State variable for tosses
int Heads; // State variable for # of heads
System.out.println("Enter number of tosses:");
Scanner input1 = new Scanner(System.in);
Toss = input1.nextInt();
for(int i = 0; i < Toss ; i++)
{
int Coin = (int) (Math.random() + .5);
System.out.print(Coin); // Prints sequence of flips
}
System.out.println("");
System.out.println("Longest sequence of heads is "); // Says largest sequence of heads
}
}
I'm stuck as to how I read the sequence and then display the longest consecutive head count.
I have written a function to do this. I take the String that you were printing and made a String out of it. I pass this string as a parameter to the function and count the consecutive 0 in it.
This is the code for the same:
import java.util.Scanner;
public class CoinFlip {
public static void main(String args[]) {
int Toss; // State variable for tosses
System.out.println("Enter number of tosses:");
Scanner input1 = new Scanner(System.in);
Toss = input1.nextInt();
StringBuffer coinSequenceBuffer = new StringBuffer(Toss);
for (int i = 0; i < Toss; i++) {
int Coin = (int) (Math.random() + .5);
System.out.print(Coin); // Prints sequence of flips
coinSequenceBuffer.append(Coin);
}
String coinSequence = coinSequenceBuffer.toString();
System.out.println("");
int numberOfConsecutiveHead = findNumberOfConsecutiveHead(coinSequence);
System.out.println("Longest sequence of heads is " + numberOfConsecutiveHead);
}
private static int findNumberOfConsecutiveHead(String coinSequence) {
int count = 1;
int max = 0;
// Starting loop from 1 since we want to compare it with the char at index 0
for (int i = 1; i < coinSequence.length(); i++) {
if (coinSequence.charAt(i) == '1') {
// Since we are not intersted in counting 1's as per the question
continue;
}
if (coinSequence.charAt(i) == coinSequence.charAt(i - 1)) {
count++;
} else {
if (count > max) { // Record current run length, is it the maximum?
max = count;
}
count = 1; // Reset the count
}
}
if (count > max) {
max = count;
}
return max;
}
}
I have tried adding comments so that you can easily understand it. Let me know if you face any issue in understanding it.
This is pretty simple. Just count zeros and reset counter when not zero.
public static void main(String... args) {
System.out.print("Enter number of tosses: ");
int[] arr = new int[new Scanner(System.in).nextInt()];
Random random = new Random();
for (int i = 0; i < arr.length; i++)
arr[i] = random.nextInt(2);
System.out.println(Arrays.toString(arr));
System.out.println("Longest sequence of heads is " + findLongestZeroSequence(arr));
}
public static int findLongestZeroSequence(int... arr) {
int res = 0;
for (int i = 0, cur = 0; i < arr.length; i++) {
if (arr[i] == 0)
res = Math.max(res, ++cur);
else
cur = 0;
}
return res;
}
Here's my go at it:
class CoinFlip {
public static void main(String args[])
{
// Get number of tosses from user
System.out.print("Enter number of tosses: ");
System.out.flush();
Scanner input1 = new Scanner(System.in);
int toss = input1.nextInt();
// Build a string of random '0's and '1's of the specified length (number of tosses)
StringBuilder sb = new StringBuilder();
for(int i = 0; i < toss ; i++)
{
long coin = Math.round(Math.random());
sb.append(coin == 0? '0' : '1');
}
String seq = sb.toString();
// Print the generated String
System.out.println(seq);
// Walk through the string tallying up runs of heads
int count = 0;
int max = 0;
for (int i = 0 ; i < seq.length() ; i++) {
if (seq.charAt(i) == '0') {
count += 1;
} else {
if (count > max)
max = count;
count = 0;
}
}
// Gotta check at the end to see if the longest sequence of heads
// was at the end of the string
if (count > max)
max = count;
// Print the length of the longest sequence
System.out.println("Longest sequence of heads is " + max);
}
}
Sample run:
Enter number of tosses: 40
1000001000000010010101011000011100001000
Longest sequence of heads is 7
Explanations after the code.
import java.util.Scanner;
public class CoinFlip {
private static final int HEADS = 0;
private static final int TAILS = 1;
public static void main(String[] args) {
Scanner input1 = new Scanner(System.in);
System.out.print("Enter number of tosses: ");
int toss = input1.nextInt();
int count = 0;
int longest = 0;
StringBuilder sb = new StringBuilder(toss);
for (int i = 0; i < toss; i++) {
int coin = (int) ((Math.random() * 10) % 2);
sb.append(coin);
System.out.printf("Got %d [%s]%n", coin, (coin == HEADS ? "HEADS" : "TAILS"));
if (coin == HEADS) {
count++;
System.out.println("count = " + count);
}
else {
if (count > longest) {
longest = count;
System.out.println("longest = " + longest);
}
count = 0;
}
}
if (count > longest) {
longest = count;
System.out.println("longest = " + longest);
}
System.out.println(sb);
System.out.print("Longest sequence of heads is " + longest);
}
}
In order to generate a random number which must be either 0 (zero) or 1 (one), I call method random() of class java.lang.Math. The method returns a double between 0.0 and 1.0. Multiplying by ten and then performing modulo 2 operation on that number returns either 0.0 or 1.0 which is a double and therefore needs to be cast to an int.
Each time the above calculation returns 0 (zero) I increment a count. If the calculation returns 1 (one) then I check whether the count is greater than longest and update longest accordingly, after which I reset the count back to zero.
Note that if the last toss is "heads" then the check for the longest sequence will not be performed. Hence I repeat the check for the longest sequence after the for loop.
At the end of the for loop, I have all the required information, i.e. the string that records all the results of all the coin tosses plus the longest sequence of heads.
Here is sample output:
Enter number of tosses: 10
Got 1 [TAILS]
Got 1 [TAILS]
Got 1 [TAILS]
Got 0 [HEADS]
count = 1
Got 1 [TAILS]
longest = 1
Got 0 [HEADS]
count = 1
Got 0 [HEADS]
count = 2
Got 1 [TAILS]
longest = 2
Got 0 [HEADS]
count = 1
Got 0 [HEADS]
count = 2
1110100100
Longest sequence of heads is 2
Create a java program that reads an integer number (NUM) and determine its reverse by using the division and remainder/modulo operators. If the last digit is zero, replace it with a one(1) before reversing the number. Output also the sum of all the digits.
import java.util.*;
public class Main {
static int replace(int number){
if (number == 0)
return 0;
int digit = number % 10;
if (digit == 0)
digit = 1;
return (number/10) * 10 + digit;
}
static int Convert(int number){
if (number == 0)
return 0;
else
return replace(number);
}
public static void main(String[] args) {
int number;
Scanner kb = new Scanner(System.in);
System.out.print("Enter the number : ");
number = kb.nextInt();
System.out.println("replace:"+replace(number));
int a, m = 0, sum = 0;
do{
a = replace(number) % 10;
m = m * 10 + a;
sum = sum + a;
number = replace(number) / 10;
}
while( replace(number) > 0);
System.out.println("Reverse:"+m);
System.out.println("Sum of digits:"+sum);
}
}
Currently the problem occurs in reversing the number because it also replace the last digit of the number, this should not happen.
Input/Output of current program
Enter the number : 2300
replace:2301
Reverse:1132
Sum of digits:7
do this instead
import java.util.*;
public class Main {
static int replace(int number){
if (number %10 == 0)
return number += 1;
return number;
}
static int Convert(int number){
if (number == 0)
return 0;
else
return replace(number);
}
public static void main(String[] args) {
int number;
Scanner kb = new Scanner(System.in);
System.out.print("Enter the number : ");
number = kb.nextInt();
int a = 0, m = 0, sum = 0;
number = replace(number);
System.out.println("replace:" + number);
do{
a = number % 10;
m = m * 10 + a;
sum = sum + a;
number /= 10;
}
while( number > 0);
System.out.println("Reverse:"+m);
System.out.println("Sum of digits:"+sum);
}
}
Your code is fundamentally wrong because of the way you are replacing your numbers.
Changes made:
Changed replacing algorithm (You cannot change all 0 values to 1 that is wrong and why you got the wrong values)
Replace the number before you enter the loop. (You don't need to replace every iteration of the loop at 3 different place)
Expected output:
Exercise from Deitel's "Java How To Program" 10th edition:
2.30 (Separating the Digits in an Integer) Write an application that inputs one number consisting of five digits from the user, separates the number into its individual digits and prints the digits separated from one another by three spaces each. For example, if the user types in the number 42339, the program should print
4 2 3 3 9
Assume that the user enters the correct number of digits. What happens when you enter a number with more than five digits? What happens when you enter a number with fewer than five digits?[Hint: It's possible to do this exercise with the techniques you learned in this chapter. You'll need to use both division and reminder operations to "pick off" each digit.]
Could someone explain to me how should I go about "picking off" individual integers using division and reminder operators?
EDIT: control structures (if / else and the like) are not allowed yet, those are explored in future chapters. Variables, arithmetic operators and comparison operators only.
You know that the number is 5 digit long.
What about
number / 10 000 to retrieve the first digit.
number = reminder
number / 1000 to retrieve the second digit.
number = reminder
number / 100 to retrieve the third digit.
number = reminder
number / 10 to retrieve the fourth digit.
and reminder is the 5th one.
Here is the answer of displaying digit in same order u have enter
import java.util.Scanner;
public class oddMethod {
public static void main(String[] args) {
System.out.println("Enter start number:");
int number=getNumber();
int last=Reverse1stTime(number);
System.out.println("Digit You Enter:"+last);
}
private static int getNumber() {
Scanner sr = new Scanner(System.in);
return sr.nextInt();
}
private static int Reverse1stTime(int number)
{ int digit=0;
int reverse=0;
while(number>0)
{
digit=number%10;
reverse=reverse*10+digit;
number=number/10;
}
return reverseAgain(reverse);
}
private static int reverseAgain(int number)
{ int digit=0;
int reverse=0;
while(number>0)
{
digit=number%10;
System.out.println(digit);
reverse=(reverse*10+digit);
number=number/10;
}
return reverse;
}
}
Input 12345
Output 12345
my small hint with division - you can divide by 10 and take a look, what is that operation giving...
More, you have to deduce if you want to learn programming.
I also just started with java and with this book, and this is the code that did the tric for me. Forgive me if i did something strange... :)
import java.util.Scanner;
public class SeparateNumber
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int nr, nr1, nr2, nr3, nr4, nr5;
System.out.print("Enter a number with 5 digits: ");
nr = in.nextInt();
nr1 = nr / 10000;
nr2 = (nr % 10000) / 1000;
nr3 = ((nr % 10000) % 1000) / 100;
nr4 = (((nr % 10000) % 1000) % 100) / 10;
nr5 = (((nr % 10000) % 1000) % 100) % 10;
System.out.printf("%d%s%d%s%d%s%d%s%d%n", nr1, " ", nr2, " ", nr3, " ", nr4, " ", nr5);
}
}
Try this:
import java.util.*;
public class DigitsDisplay
{
public static void main (String[] args)
{
Scanner input = new Scanner (System.in);
int digit;
System.out.print("Enter a positive number: ");
digit = input.nextInt();
int power = 1;
while (power <= digit) {
power *= 10;
}
power /= 10;
while (power > 0) {
System.out.println(digit/power);
digit %= power;
power /= 10;
}
}
}
Try something like this
String str1 = "";
int a = 12345;
while(a>0)
{
int b = a%10;
str1 = str1 + String.valueOf(b+" ");
a = a/10;
}
StringBuilder str = new StringBuilder(str1);
System.out.println(str.reverse());
Below code handles splitting on any int in integer range.
Steps:
Convert int to String
Convert each character of String to int by using Integer.parseInt
Store int digits in int[]
Print int[]
Sample code:
import java.util.*;
public class SplitDigits{
public static void main(String args[]) throws Exception {
System.out.println("Enter number:");
Scanner sc = new Scanner(System.in);
int number = sc.nextInt();
System.out.println("You have entered:"+number);
String str = String.valueOf(number);
int length = str.length();
if ( length > 0){
int[] digits = new int[length];
for ( int i=0; i < length; i++){
digits[i] = Integer.parseInt(String.valueOf(str.charAt(i)));
}
for ( int i=0; i < digits.length; i++){
System.out.println("Digits:"+digits[i]);
}
}
}
}
output:
java SplitDigits
Enter number:
123456789
You have entered:123456789
Digits:1
Digits:2
Digits:3
Digits:4
Digits:5
Digits:6
Digits:7
Digits:8
Digits:9
import java.util.Scanner;
public class DigitSeparator{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("Enter a 5 digit number: ");
int number = input.nextInt();
System.out.print((number / 10000)+ " ");
int divider = 10000;
int mod = number % 10000;
for(int i = 1; i <= 4; i++){
divider /= 10;
System.out.print( mod/divider +" ");
mod %= divider;
}
System.out.println();
}
}
first import java.util.Scanner; berfore your
class.
and write this code in your main method.
Scanner input = new Scanner(System.in);
System.out.print("Enter a five digit number: ");
int number = input.nextInt();
int first_digit = number / 10000;
int second_digit = (number % 10000) / 1000 ;
int third_digit = (number % 1000) / 100;
int fourth_digit = (number % 100) / 10;
int fifth_digit = (number % 10);
System.out.printf("%d %d %d %d
%d%n", first_digit, second_digit, third_digit, fourth_digit, fifth_digit);
package chapter1;
import java.util.Scanner;
public class Exercise3 {
public static void main (String[] args){
Scanner scan = new Scanner (System.in);
System.out.print ("Enter a number that consist of 5 digits: ");
int num =scan.nextInt();
int digit1 =num / 10000;
int digit2 =(( num % 10000) / 1000 ); // the modulus answer of num/10000 is divided by 1000
int digit3 =( ( num % 1000) / 100 );
int digit4 = ( ( num% 100 ) / 10 );
int digit5 = ( num % 10);
System.out.print (digit1+"\t");
System.out.print(digit2+"\t");
System.out.print(digit3+"\t");
System.out.print(digit4+"\t");
System.out.println(digit5+"\t");
}
}
Answer is:
//your package name
import java.util.Scanner; //for input the userin
public class SeperateDigit {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.printf("Enter a 5 digit number: ");
int number = input.nextInt();
int number1 = number/100000;
int arrange = number%10000;
int number2 = arrange/1000;
int number3 = (arrange % 1000) /100;
int number4 =(( arrange % 1000) % 100) / 10;
int number5 = ((arrange % 1000) % 100) % 10;
System.out.printf("%d %d %d %d %d", number1,number2,number3,number4, number5);
}
}
and Result is
Enter a 5 digit number: 422339
4 2 3 3 9
This function its only working for certain numbers, but for 15, or 5 it does not give me correct next prime.
public static int nextPrime(int n) {
boolean isPrime = false;
int m = (int) Math.ceil(Math.sqrt(n));
int start = 3;
if (n % 2 == 0) {
n = n + 1;
}
while (!isPrime) {
isPrime = true;
for (int i = start; i <= m; i = i + 2) {
if (n % i == 0) {
isPrime = false;
break;
}
}
if (!isPrime) {
n = n + 2;
}
}
return n;
}
You don't need to go upto sqrt(n), you need to go upto sqrt(number) that you are evaluating
for example consider you pass n = 5
it will start loop from 3 and it will end the loop at 4 that is not what you need to find next prime number
outer loop
start from n + 1 until you find prime
inner loop
you should start from 3 and sqrt(numberUnderIteration)
You're setting your boundary at the square root of the original number only. In order for you to check if every next number works, you need to recalculate the boundary whenever the n value is changed. So, put int m = (int) Math.ceil(Math.sqrt(n)); inside of your while loop.
You also need to increment n by 1 before you start any calculations, or it will accept n itself as a prime number if it is one. For example, nextPrime(5) would return 5 because it passes the conditions.
And finally, you don't need to increment n by 2 at the end of your while loop because if you are on an even number, it will break out (keep adding 2 to an even number will always be even). I've commented the part of your code that I changed:
public static int nextPrime(int n) {
boolean isPrime = false;
int start = 2; // start at 2 and omit your if statement
while (!isPrime) {
// always incrememnt n at the beginning to check a new number
n += 1;
// redefine max boundary here
int m = (int) Math.ceil(Math.sqrt(n));
isPrime = true;
// increment i by 1, not 2 (you're skipping numbers...)
for (int i = start; i <= m; i++) {
if (n % i == 0) {
isPrime = false;
break;
}
}
// you don't need your "if (!isPrime)..." because you always increment
}
return n;
}
public static void main(String[] args) {
System.out.println(nextPrime(15)); // 17
System.out.println(nextPrime(5)); // 7
System.out.println(nextPrime(8)); // 11
}
You need to compute m inside the for loop.
while (!isPrime) {
isPrime = true;
int m = (int) Math.ceil(Math.sqrt(n));
// do other stuff
Your code works fine except when a prime number is given as input, your method returns input itself.
Example if 5 is your input nextPrime(5) returns 5. If you want 7 (next prime number after 5) to be returned in this case.
Just add n=n+1; at the start of your method. Hope this helps
Just for fun, I coded a quick Prime class that tracks known primes, giving a huge performance boost to finding multiple large primes.
import java.util.ArrayList;
public class Primes {
private static ArrayList<Integer> primes = new ArrayList<Integer>();
public static int nextPrime(int number){
//start it off with the basic primes
if(primes.size() == 0){
primes.add(2);
primes.add(3);
primes.add(5);
primes.add(7);
}
int idx = primes.size()-1;
int last = primes.get(idx);
//check if we already have the prime we are looking for
if(last > number){
//go to the correct prime and return it
boolean high = false;
boolean low = false;
int prevIdx = 0;
int spread = 0;
//keep finagling the index until we're not high or low
while((high = primes.get(idx-1) > number) || (low = primes.get(idx) <= number)){
spread = Math.abs(prevIdx-idx);
//because we always need to move by at least 1 or we will get stuck
spread = spread < 2 ? 2: spread;
prevIdx = idx;
if(high){
idx -= spread/2;
} else if(low){
idx += spread/2;
}
};
return primes.get(idx);
}
/*FIND OUR NEXT SERIES OF PRIMES*/
//just in case 'number' was prime
number++;
int newPrime = last;
//just keep adding primes until we find the right one
while((last = primes.get(primes.size()-1)) < number){
//here we find the next number
newPrime += 2;
//start with the assumption that we have a prime, then try to disprove that
boolean isPrime = true;
idx = 0;
int comparisonPrime;
int sqrt = (int) Math.sqrt(newPrime);
//make sure we haven't gone over the square root limit- also use post-increment so that we use the idx 0
while((comparisonPrime = primes.get(idx++)) <= sqrt){
if(newPrime % comparisonPrime == 0){
isPrime = false;
}
}
if(isPrime){
primes.add(newPrime);
}
}
return last;
}
}
And here is the test:
public class Test {
public static void main(String[] args){
long start;
long end;
int prime;
int number;
number = 1000000;
start = System.currentTimeMillis();
prime = Primes.nextPrime(number);
end = System.currentTimeMillis();
System.out.println("Prime after "+number+" is "+prime+". Took "+(end-start)+" milliseconds.");
number = 500;
start = System.currentTimeMillis();
prime = Primes.nextPrime(number);
end = System.currentTimeMillis();
System.out.println("Prime after "+number+" is "+prime+". Took "+(end-start)+" milliseconds.");
number = 1100000;
start = System.currentTimeMillis();
prime = Primes.nextPrime(number);
end = System.currentTimeMillis();
System.out.println("Prime after "+number+" is "+prime+". Took "+(end-start)+" milliseconds.");
}
}
This results in the following output:
Prime after 1000000 is 1000003. Took 384 milliseconds.
Prime after 500 is 503. Took 10 milliseconds.
Prime after 1100000 is 1100009. Took 65 milliseconds.
As you can see, this takes a long time the first iteration, but we only have to perform that operation once. After that, our time is cut down to almost nothing for primes less than our first number (since it's just a lookup), and it is very fast for primes that are just a bit bigger than our first one (since we have already done most of the work).
EDIT: Updated search for existing primes using a variation on a Binary Search Algorithm. It cut the search time at least in half.
import java.util.Scanner;
class Testing
{
public static void main(String Ar[])
{
int a = 0, i, j;
Scanner in = new Scanner(System.in);
a = in.nextInt();
for (j = a + 1;; j++)
{
for (i = 2; i < j; i++)
{
if (j % i == 0)
break;
}
if (i == j)
{
System.out.println(j);
break;
}
}
}
}
Here is the perfect code for finding next prime for a given number.
public class NextPrime
{
int nextPrime(int x)
{
int num=x,j;
for( j=num+1;;j++)
{
int count=0;
for(int i=1;i<=j;i++)
{
if(j%i==0)
{
count++;
//System.out.println("entered");
}
//System.out.println(count);
}
if(count==2)
{
System.out.println(" next prime is ");
break;
}
}return j;
}
public static void main(String args[])
{
NextPrime np = new NextPrime();
int nxtprm = np.nextPrime(9);
System.out.println(nxtprm);
}
}
//I hope the following code works exactly.
import java.util.Scanner;
public class NextPrime {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a positive integer number : ");
int n = scanner.nextInt();
for (int x = n + 1;; x++) {
boolean isPrime = true;
for (int i = 2; i < x / 2; i++) {
if (x % i == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
System.out.println("Next prime is : " + x);
break;
}
}
}
}