I am attempting to write a program in java that flips an imaginary coin and outputs the flips and then when a certain side has been flipped 3 times, it stops and tells you the number of times it flipped. My program doesn't seem to be working
My code is below:
import java.util.*;
public class FlipperThree {
public static void main(String[] args) {
boolean fin = false;
while(!fin){
System.out.println("Welcome to Flipper!");
int h = 0;
int hcount = 0;
int tcount = 0;
int ocount = 0;
String random;
String[] ht;
boolean done = false;
while(!done){
for(hcount<3||tcount<3){ht = new String[] {"Heads","Tails"};
Random r =new Random();
random = ht[r.nextInt(ht.length)];
System.out.println(random);
}
if (hcount!=3||tcount!=3){
if(random == ht[h]){
hcount++;
ocount++;
tcount = 0;
}else{
hcount = 0;
tcount++;
ocount++;
}
}else{
System.out.println("BINGO!That only took " + ocount+" flips to get 3 in a row!");
done = true;
}
}
}fin = true;
}
}
In general your program is much more complicated than necessary. You only need a single loop
You were using == to compare strings. Instead of random == ht[h] you should say random.equals(ht[h])
Instead of looping while either heads or tail counts are less than 3, you only want to keep looping while both are less than three. So instead of hcount!=3 || tcount!=3 it's hcount!=3 && tcount!=3
.
public class FlipperThree {
public static void main(String[] args) {
System.out.println("Welcome to Flipper!");
int h = 0;
int hcount = 0;
int tcount = 0;
int ocount = 0;
String[] ht = new String[] {"Heads","Tails"};
Random r =new Random();
while (hcount < 3 && tcount < 3) {
String random = ht[r.nextInt(ht.length)];
System.out.println(random);
if(random.equals(ht[h])){
hcount++;
ocount++;
tcount = 0;
}
else{
hcount = 0;
tcount++;
ocount++;
}
}
System.out.println("BINGO!That only took " + ocount+" flips to get 3 in a row!");
}
}
$ java FlipperThree
Welcome to Flipper!
Tails
Heads
Heads
Tails
Heads
Heads
Tails
Tails
Tails
BINGO!That only took 9 flips to get 3 in a row!
Remove the for and init ht once and remove your first while too and change || to &&:
import java.util.*;
public class FlipperThree {
public static void main(String[] args) {
System.out.println("Welcome to Flipper!");
int h = 0;
int hcount = 0;
int tcount = 0;
int ocount = 0;
String random;
String[] ht = new String[] {"Heads","Tails"};
boolean done = false;
while(!done){
Random r =new Random();
random = ht[r.nextInt(ht.length)];
System.out.println(random);
if (hcount!=3 && tcount!=3){
ocount++;
if(random == ht[h]){
hcount++;
tcount = 0;
}else{
hcount = 0;
tcount++;
}
}else{
System.out.println("BINGO!That only took " + ocount+" flips to get 3 in a row!");
done = true;
}
}
}
You can achieve this with much simpler code when you realize that you just need to keep track of the number of consecutive coin faces. It doesn't matter what face it is:
/**
* return:
* the number of coin tosses until you get the same face n consecutive times
*/
static int numTossesUntilNConsecutiveFaces(int n) {
Random toss = new Random();
// This counts the number of consecutive faces following a given face
// For example:
// for sequence 1 0, numConsecutive == 0
// for sequence 1 1, numConsecutive == 1
// for sequence 0 0 0, numConsecutive == 2
int numConsecutives = 0;
int numTosses = 0;
// Initialize the lastCoin value as -1, so the first coin won't be equal to it
int lastCoin = -1;
do {
// The result of the toss will be 0 or 1 (head or tails)
int coin = toss.nextInt(2);
if (coin == lastCoin) {
// If the current coin is the same as the last coin, increment the counter
numConsecutives++;
} else {
// If it is different, reset the counter
numConsecutives = 0;
}
// Make this coin the last coin
lastCoin = coin;
numTosses++;
// Stop when the number of consecutives is n - 1.
// For n == 3, that is when the last three numbers were 1 1 1 or 0 0 0
} while (numConsecutives < n - 1);
return numTosses;
}
Then you just need to call:
int tosses = numTossesUntilNConsecutiveFaces(3);
public class FlipperThree {
public static void main(String[] args) {
System.out.println("Welcome to Flipper!");
int previousFlip = -1;
int continuousFlip = 0;
int totalFlips = 0;
String[] ht = new String[] {"Heads","Tails"};
Random r = new Random();
while (continuousFlip < 3) {
int r = r.nextInt(ht.length);
totalFlips++;
System.out.println(ht[r]);
if(previousFlip == r){
continuousFlip++
} else {
continuousFlip = 1;
previousFlip = r;
}
}
System.out.println("BINGO!That only took " + totalFlips +" flips to get 3 in a row!");
}
}
Just wanted to show a shorter version. Whole point is that you don't need to keep track of BOTH the heads or tails, you just need to keep track of how much you've flipped the same number consequtively. Very minor optimization concerning real world performance, but still an improvement :)
Related
Nothing will print when run. Where's the error?
In this project you will simulate two games. In the first game, roll one die four times and record a "win" if a six is rolled at least once during the four rolls, otherwise record a "loss". In the second game, roll two die twenty-four times and record a "win" if two six's are rolled at least once during the twenty-four rolls, otherwise record a "loss". Your program should simulate running each game a million times and output the number of wins and losses for each game.
import java.util.Random;
public class Driver {
public static void main(String[] args) {
int win6 = 0;
int lose6 = 0;
int win24 = 0;
int lose24 = 0;
int n = 100000000;
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= 4; j++){
Random r = new Random();
int next = r.nextInt(1-6);
if (next == 6){
win6 = win6 + 1;
break;
}
}
lose6 = 100000000 - win6;
for (int u = 0; u <= 24; u++){
Random r = new Random();
Random t = new Random();
int next1 = r.nextInt(1-6);
int next2 = t.nextInt(1-6);
if (next1 == 6 && next2 == 6){
win24 = win24 + 1;
break;
}
}
lose24 = 100000000 - win24;
}
System.out.println(win6);
System.out.println(lose6);
System.out.println(win24);
System.out.println(lose24);
}
}
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
import java.util.Random;
public class RollingDice {
public static void main(String[] args){
int numSides = 6;
Random ranGen = new Random();
for (int i =1; i <= 20; i++){
if (ranGen.nextInt(numSides) == 3) {
System.out.println("A 3 has been rolled!");
}
}}}
this is my code so far. It prints the message every time the number 3 is rolled. I am new to coding, so please bear with me. What i want to do next is store the numbers of times 3 is rolled so when the loop exits, it displays the final count of the number of times 3 was actually rolled in that process. That making the end result be some number which represents the number of times the number 3 was rolled by the system.
Thanks!
-Sail
Define a count.
int count = 0;
Increase count each time you encounter a roll of 3. Inside of the loop, if you roll a 3:
count = count + 1;
Print count outside of the loop.
System.out.printf("A 3 was been rolled %d times.\n", count);
Random ranGen = new Random();
int numberOfThrees = 0;
for (int i =1; i <= 20; i++){
if (ranGen.nextInt(numSides) == 3) {
++numberOfThrees;
}
}
System.out.println(numberOfThrees);
Like this:
import java.util.Random;
public class RollingDice {
public static void main(String[] args){
int numSides = 6;
int threes = 0;
Random ranGen = new Random();
for (int i =1; i <= 20; i++) {
if (ranGen.nextInt(numSides) == 3) {
System.out.println("A 3 has been rolled!");
threes++
}
}
System.out.println("A 3 has been rolled " + threes + " times!");
}}
Actually, what you are recording is the number of 4's that have been rolled, since nextInt returns a number between 0 and 5.
You could simply have a counter
import java.util.Random;
public class RollingDice {
public static void main(String[] args){
int numSides = 6;
int cnt = 0; // <-- Declare a counter
Random ranGen = new Random();
for (int i =1; i <= 20; i++){
if (ranGen.nextInt(numSides) == 3) {
System.out.println("A 3 has been rolled!");
cnt++; // <-- increment counter
}
}
System.out.printf("A 3 has been rolled %d times!\n", cnt);
}
I tried to create a simple lottery program. Here is a problem: it still prints same numbers. For example I got 33 21 8 29 21 10 as output. Everytime when random number is generated, code checks if that number is already generated, then it creates a new random number but after that it doesn't check again. I couldn't find a way to do that.
public static void main(String[] args)
{
int[] lottery = new int[6];
int randomNum;
for (int i = 0; i < 6; i++)
{
randomNum = (int) (Math.random() * 50); //Random number created here.
for (int x = 0; x < i; x++)
{
if (lottery[i] == randomNum) // Here, code checks if same random number generated before.
{
randomNum = (int) (Math.random() * 50);//If random number is same, another number generated.
}
}
lottery[i] = randomNum;
}
for (int i = 0; i < lottery.length; i++)
System.out.print(lottery[i] + " ");
}
There are 2 problems with your code:
you check if lottery[i] and randomNum are the same, it should be lottery[x]
when you re-generate a random number, you don't check it against the first numbers in lottery.
Here is a corrected version:
public static void main(String[] args) {
int[] lottery = new int[6];
int randomNum;
for (int i = 0; i < 6; i++) {
randomNum = (int) (Math.random() * 50); // Random number created here.
for (int x = 0; x < i; x++) {
if (lottery[x] == randomNum) // Here, code checks if same random number generated before.
{
randomNum = (int) (Math.random() * 50);// If random number is same, another number generated.
x = -1; // restart the loop
}
}
lottery[i] = randomNum;
}
for (int i = 0; i < lottery.length; i++)
System.out.print(lottery[i] + " ");
}
You are changing the random number while you are checking it. You need to pick one random number and check whether it is present or not.
BTW A shorter approach is to use a shuffle.
// give me all the number 1 to 50
List<Integer> list = IntStream.range(1, 51).boxed().collect(Collectors.toList());
// shuffle them.
Collections.shuffle(list);
// give me the first 6
System.out.println(list.subList(0, 6));
A simple solution, between the first (who could be very abstract for a not Java programmer) and the 2nd (not assuring the unicity of the number list).
Collection<Integer> liste = new ArrayList<Integer>();
for (int i = 0; i < 6; i++)
{
Boolean ap = false;
while (!ap)
{
Integer randomNumber = (int) (Math.random() * 50);
if (! liste.contains(randomNumber)){
liste.add(randomNumber);
ap = true;
}
}
}
for (Integer liste1 : liste) {
System.out.print(liste1+" ");
}
try this one, it creates 12 x (6 out of 45)
public static void main(String[] args) {
SecureRandom random = new SecureRandom();
for (int i = 0; i < 12; i++){
Integer[] tipp = new Integer[6];
int n = 0;
do {
int r = random.nextInt(45) + 1;
if (Arrays.asList(tipp).indexOf(r)<0){
tipp[n]= r;
n++;
}
} while (n<=5);
Arrays.sort(tipp);
System.out.println(Arrays.toString(tipp));
}
}
public static void main(String[] arg) {
int[] lottery = new int[6];
int randomNum;
c1:
for (int i = 0; i < 6; i++) {
randomNum = (int) (Math.random() * 50); // Random number created here.
if(randomNum == 0) {
continue c1;
}
for (int x = 0; x < i; x++) {
if (lottery[x] == randomNum ) // Here, code checks if same random number generated before.
{
randomNum = (int) (Math.random() * 50);// If random number is same, another number generated.
x = -1; // restart the loop
}
}
lottery[i] = randomNum;
}
for (int i = 0; i < lottery.length; i++)
System.out.print(lottery[i] + " ");
}
This is the object class for making a ticket, it will create ONE ticket with ascending values at which whatever parameters you choose. This program won't run until you have a main method that you call. Make sure to import TreeSet.
import java.util.TreeSet;
public class TicketMaker{
private int numbersPerTicket;
private int lowestNumber;
private int highestNumber;
TicketMaker(){
numbersPerTicket=0;
lowestNumber=0;
highestNumber=0;
}
TicketMaker(int numbersPerTicket,int lowestNumber,int highestNumber){
if(numbersPerTicket > 0 && lowestNumber >= 0 && highestNumber >= lowestNumber){
this.numbersPerTicket=numbersPerTicket;
this.lowestNumber=lowestNumber;
this.highestNumber=highestNumber;
}
}
public boolean printTicket(int numbersPerTicket,int lowestNumber,int highestNumber){
if(numbersPerTicket > 0 && lowestNumber >= 0 && highestNumber >= lowestNumber){
if(numbersPerTicket > highestNumber){
System.out.println("Error not in-bounds");
return false;
}
int rand;
int count=0;
System.out.println("[Ticket Printed]");
TreeSet<Integer> set = new TreeSet<>();
do{
rand = (int)(Math.random()*highestNumber)+lowestNumber;
set.add(rand);
count++;
}while(set.size() != numbersPerTicket);
System.out.println(set);
return true;
}
else{
System.out.println("Error not in-bounds");
return false;
}
}
public boolean isValidTicketData(int numbers,int lowest,int highest){
if(lowest != 1){
if(highest == numbers)
return false;
}
if(numbers <= highest){
if(numbers > 0 && lowest >= 0 && highest >= lowest)
return true;
}
return false;
}
}
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;
}
}
}
}