Calculating the 10001 prime number, no output is printed - java

public class Prime
{
public static void main(String [] args)
{
int num = 3;
int counter = 1;
boolean flag = true;
while(counter < 10001)
{
for(int i = 2; i < num; i++)
{
if(num%i==0)
{
flag = false;
}
}
if(flag)
{
counter++;
}
num++;
}
System.out.println(num);
}
}
Whenever I run this code, no result is printed out. I'm assuming its because the code is inefficient, but I don't know what is wrong with this code.

Your problem is that you don't reset flag to true before the for loop; so once it is false, it remains false, so counter is never incremented, meaning the while loop guard never becomes false.
This is an example of why you should declare variables in the tightest possible scope (i.e. inside the while loop).
while(counter < 10001)
{
int flag = true;
for (...) {...}
if (flag) { counter++; }
// ...
}
It's also an example of why you should make sure your code is correct before you think about whether it is efficient. Had you debugged the code (or even just added in a few System.out.printlns), you could have found that it wasn't actually doing the right thing.

As mentioned by #AndyTurner you should declare flag = true; in while loop and also there is a slight error in your logic for finding the prime number.
You are incrementing the num after it is checked for prime. So, if your 3rd prime is 5, then it will print 6 as the answer. lly, if your 10001th prime is X, then it will print X + 1 as the answer.
I have posted the correct logic for your problem below. I hope it helps you.
public class Main
{
public static void main(String [] args)
{
int num = 2;
int counter = 1;
boolean flag = true;
while(counter < 10001)
{
flag = true;
num++;
for(int i = 2; i < num; i++)
{
if(num%i==0)
{
flag = false;
}
}
if(flag)
{
counter++;
}
}
System.out.println(num);
}
}

Its not printing cause its going in infinite loop as counter is not incremented once flag become false
public static void main(String [] args)
{
int num = 3;
int counter = 1;
boolean flag = true;
while(counter < 10001)
{
flag = true;
for(int i = 2; i < num; i++)
{
if(num%i==0)
{
flag = false;
}
}
if(flag)
{
counter++;
}
num++;
}
System.out.println(num);
}
Try this. hope it helped

Related

randomly generate 100 unique numbers using Math.random [duplicate]

my intend is to use simplest java (array and loops) to generate random numbers without duplicate...but the output turns out to be 10 repeating numbers, and I cannot figure out why.
Here is my code:
int[] number = new int[10];
int count = 0;
int num;
while (count < number.length) {
num = r.nextInt(21);
boolean repeat = false;
do {
for (int i=0; i<number.length; i++) {
if (num == number[i]) {
repeat = true;
} else if (num != number[i] && i == count) {
number[count] = num;
count++;
repeat = true;
}
}
} while (!repeat);
}
for (int j = 0; j < number.length; j++) {
System.out.print(number[j] + " ");
}
How about you use a Set instead? If you also want to keep track of the order of insertion you can use a LinkedHashSet.
Random r = new Random();
Set<Integer> uniqueNumbers = new HashSet<>();
while (uniqueNumbers.size()<10){
uniqueNumbers.add(r.nextInt(21));
}
for (Integer i : uniqueNumbers){
System.out.print(i+" ");
}
A Set in java is like an Array or an ArrayList except it handles duplicates for you. It will only add the Integer to the set if it doesn't already exist in the set. The class Set has similar methods to the Array that you can utilize. For example Set.size() is equivalent to the Array.length and Set.add(Integer) is semi-equivalent to Array[index] = value. Sets do not keep track of insertion order so they do not have an index. It is a very powerful tool in Java once you learn about it. ;)
Hope this helps!
You need to break out of the for loop if either of the conditions are met.
int[] number = new int[10];
int count=0;
int num;
Random r = new Random();
while(count<number.length){
num = r.nextInt(21);
boolean repeat=false;
do{
for(int i=0; i<number.length; i++){
if(num==number[i]){
repeat=true;
break;
}
else if(i==count){
number[count]=num;
count++;
repeat=true;
break;
}
}
}while(!repeat);
}
for(int j=0;j<number.length;j++){
System.out.print(number[j]+" ");
}
This will make YOUR code work but #gonzo proposed a better solution.
Your code will break the while loop under the condition: num == number[i].
This means that if the pseudo-generated number is equal to that positions value (the default int in java is 0), then the code will end execution.
On the second conditional, the expression num != number[i] is always true (otherwise the code would have entered the previous if), but, on the first run, when i == count (or i=0, and count=0) the repeat=true breaks the loop, and nothing else would happen, rendering the output something such as
0 0 0 0 0 0...
Try this:
int[] number = new int[10];
java.util.Random r = new java.util.Random();
for(int i=0; i<number.length; i++){
boolean repeat=false;
do{
repeat=false;
int num = r.nextInt(21);
for(int j=0; j<number.length; j++){
if(number[j]==num){
repeat=true;
}
}
if(!repeat) number[i]=num;
}while(repeat);
}
for (int k = 0; k < number.length; k++) {
System.out.print(number[k] + " ");
}
System.out.println();
Test it here.
I believe the problem is much easier to solve. You could use a List to check if the number has been generated or not (uniqueness). Here is a working block of code.
int count=0;
int num;
Random r = new Random();
List<Integer> numbers = new ArrayList<Integer>();
while (count<10) {
num = r.nextInt(21);
if(!numbers.contains(num) ) {
numbers.add(num);
count++;
}
}
for(int j=0;j<10;j++){
System.out.print(numbers.get(j)+" ");
}
}
Let's start with the most simple approach, putting 10 random - potentially duplicated - numbers into an array:
public class NonUniqueRandoms
{
public static void main(String[] args)
{
int[] number = new int[10];
int count = 0;
while (count < number.length) {
// Use ThreadLocalRandom so this is a contained compilable unit
number[count++] = ThreadLocalRandom.current().nextInt(21);
}
for (int j = 0; j < number.length; j++) {
System.out.println(number[j]);
}
}
}
So that gets you most of the way there, the only thing you know have to do is pick a number and check your array:
public class UniqueRandoms
{
public static void main(String[] args)
{
int[] number = new int[10];
int count = 0;
while (count < number.length) {
// Use ThreadLocalRandom so this is a contained compilable unit
int candidate = ThreadLocalRandom.current().nextInt(21);
// Is candidate in our array already?
boolean exists = false;
for (int i = 0; i < count; i++) {
if (number[i] == candidate) {
exists = true;
break;
}
}
// We didn't find it, so we're good to add it to the array
if (!exists) {
number[count++] = candidate;
}
}
for (int j = 0; j < number.length; j++) {
System.out.println(number[j]);
}
}
}
The problem is with your inner 'for' loop. Once the program finds a unique integer, it adds the integer to the array and then increments the count. On the next loop iteration, the new integer will be added again because (num != number[i] && i == count), eventually filling up the array with the same integer. The for loop needs to exit after adding the unique integer the first time.
But if we look at the construction more deeply, we see that the inner for loop is entirely unnecessary.
See the code below.
import java.util.*;
public class RandomDemo {
public static void main( String args[] ){
// create random object
Random r = new Random();
int[] number = new int[10];
int count = 0;
int num;
while (count < number.length) {
num = r.nextInt(21);
boolean repeat = false;
int i=0;
do {
if (num == number[i]) {
repeat = true;
} else if (num != number[i] && i == count) {
number[count] = num;
count++;
repeat = true;
}
i++;
} while (!repeat && i < number.length);
}
for (int j = 0; j < number.length; j++) {
System.out.print(number[j] + " ");
}
}
}
This would be my approach.
import java.util.Random;
public class uniquerandom {
public static void main(String[] args) {
Random rnd = new Random();
int qask[]=new int[10];
int it,i,t=0,in,flag;
for(it=0;;it++)
{
i=rnd.nextInt(11);
flag=0;
for(in=0;in<qask.length;in++)
{
if(i==qask[in])
{
flag=1;
break;
}
}
if(flag!=1)
{
qask[t++]=i;
}
if(t==10)
break;
}
for(it=0;it<qask.length;it++)
System.out.println(qask[it]);
}}
public String pickStringElement(ArrayList list, int... howMany) {
int counter = howMany.length > 0 ? howMany[0] : 1;
String returnString = "";
ArrayList previousVal = new ArrayList()
for (int i = 1; i <= counter; i++) {
Random rand = new Random()
for(int j=1; j <=list.size(); j++){
int newRand = rand.nextInt(list.size())
if (!previousVal.contains(newRand)){
previousVal.add(newRand)
returnString = returnString + (i>1 ? ", " + list.get(newRand) :list.get(newRand))
break
}
}
}
return returnString;
}
Create simple method and call it where you require-
private List<Integer> q_list = new ArrayList<>(); //declare list integer type
private void checkList(int size)
{
position = getRandom(list.size()); //generating random value less than size
if(q_list.contains(position)) { // check if list contains position
checkList(size); /// if it contains call checkList method again
}
else
{
q_list.add(position); // else add the position in the list
playAnimation(tv_questions, 0, list.get(position).getQuestion()); // task you want to perform after getting value
}
}
for getting random value this method is being called-
public static int getRandom(int max){
return (int) (Math.random()*max);
}

sum of all prime numbers between 100 and 200

I'm actually about to loose my mind... The code I wrote displays every kind of "sum" and "count" between the actual last result I want to display with System.out.print(...). Can someone help me please? What did I do wrong for it to display everything?
public class Prim {
public static void main(String[] args) {
int end = 11;
int count = 1;
long sum = 0;
for (int number = 10; count<=end; number++) {
if (isPrim(number)) {
sum = sum + number;
count++;
System.out.println(sum);
}
}
}
public static boolean isPrim(int number){
for (int i=2; i<number; i++) {
if (number % i == 0) {
}
}
return true;
}
}
A few things.
First, your isPrim can be optimised so that i only increments until sqrt(number).
Second, you need to return false if (number%i == 0) is true. Right now, it's always returning true, which is why your code is outputting all sums.
Third, you need to change istPrimeZahl to isPrim (or vice versa), as you haven't defined istPrimeZahl anywhere.
Fourth, you can change sum = sum + number to simply sum += number.
Finally, you probably want to move your System.out.print line two lines below, so that it only prints the sum after the loop has ended, not at every iteration of the loop.
(Also, you might want to change your for loop so that it starts at 100, not 10 :) )
If you want the final version, I've pasted it here:
public class Prim {
public static void main(String[] args) {
int end = 200;
int count = 0;
long sum = 0;
for (int number = 100; number<=end; number++) {
if (isPrim(number)) {
sum += number;
count++;
System.out.println(sum);
}
}
}
public static boolean isPrim(int number){
for (int i=2; i*i<=number; i++) {
if (number % i == 0) {
return false;
}
}
return true;
}
}
The isPrim function is missing a 'return false' after the if statement. This means that isPrim will always return true, and consequently every number will get written to the console.
The System.out.print is also within for-loop, so it will print an updated sum each time. It's unclear if this is intentional, but if you want to only get a single result then that should also be moved two lines lower.
For sum of prime numbers between 100 to 200, try this code:
public class Primzahlen {
public static void main(String[] args) {
int sum = 0;
for (int i = 100; i < 200; i++)
if (isPrim(i))
sum += i;
System.out.print(sum);
}
public static boolean isPrim(int num) {
for (int i = 2; i <= Math.sqrt(num); i++)
if (num % i == 0)
return false;
return true;
}
}

Why won't my while loop terminate?

I've noticed when using while loops in my java programs that when using a boolean type to terminate it does not seem to be working. I typed up something simple to test it. The code completes through i = 9 and then test is printed out as false.
public class LoopTesting {
public static void main(String[] args) {
boolean test = true;
while(test) {
for (int i = 1; i < 10; i++) {
System.out.println(i);
if(i == 5) test = false;
}
}
System.out.println(test);
}
}
EDIT: In response to afzalex's answer I tested this code:
while(test) {
for (int i = 1; i < 10; i++) {
System.out.println(i);
}
test = false;
for(int i = 11; i < 20; i++) {
System.out.println(i);
}
}
and it prints to 19.
You changed test value inside for loop. but condition for for loop is i < 10, not test.
So for loop go on iterating until it ends.
Then while is terminated as you had set test as false when control was inside for loop.
This is what you want
while(test) {
for (int i = 1; i < 10; i++) {
System.out.println(i);
if(i == 5) {
test = false;
break;
}
}
}
or more simply
int i = -1;
while(test) {
i++;
System.out.println(i);
if(i == 5) {
test = false;
}
}
The issue with your while loop not closing is because you have an embedded for loop in your code. What happens, is your code will enter the while loop, because while(test) will result in true. Then, your code will enter the for loop. Inside of your for loop, you have the code looping from 1-10. This loop is based off of the Integer value i. The inside loop is basically saying while(i < 10), so this inside loop is not effected by the boolean value of test.
while(test) { // This loop will continue to run until test == false
for (int i = 1; i < 10; i++) { // This loop will continue to run until i > 9
test = false; // This will execute on the first loop of the inner loop, but it is not checked at the outer loop until the inner loop is complete
}
}
Hope that makes sense. Your issue is that the boolean is corresponding to the outer loop, nothing is stopping the inner loop from running.
You have an error in your logic. The test variable isn't getting checked until your inner for-loop completes. If you only want to iterate 5 times, you can do this:
while(test) {
for (int i = 1; i < 10; i++) {
System.out.println(i);
if(i == 5){
test = false;
break;
}
}
}
But you probably want to do something like this:
...
int i = 1;
while(test) {
if(i == 5)
test = false
else i++;
}
Here is how you second question code looks like if you replace while and for with a simple if/goto. Maybe this is easier to understand for you:
loopA: // while
if (test) {
int i1 = 1;
loopB: // for 1
if (i1 < 10) {
System.out.println(i1);
i1++;
goto loopB;
}
test = false;
int i2= 11;
loopC: // for 2
if (i2 < 20) {
System.out.println(i2);
i2++;
goto loopC;
}
goto loopA;
}
System.out.println(test);

Errors in Java program that is supposed to show the 10,000th prime number? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Here is my code, not sure what went wrong! Any mistakes I've made?
BTW: The first program in this code is designed to count the number of primes less than 1,000 just to avoid any confusion.
public class AnalyzingPrime
{
public static boolean isPrime (int n)
{
if (n==1)
return false;
for (int i = 2; i < n; i++)
{
if (n%i==0)
return false;
}
return true;
}
public static void main (String [] args)
{
int numberofPrimes = 0;
int counter = 0;
int number = 10000;
for (int i = 2; i <= number; i++)
{
if (isPrime(i) == true)
{
counter++;
}
}
System.out.println("There are "+counter+" prime numbers.");
System.out.println("And if you care, the 10,000nth prime number is "+ nthPrime(10000)+".");
}
public static int nthPrime (int n)
{
int i = 0;
int nthcounter = 0;
while (nthcounter <= n)
{
i++;
if(isPrime(i) == true)
{
nthcounter++;
}
}
return nthcounter;
}
}
I don't think there is an error, Its your method that not correct.
public static int nthPrime (int n)
{
int i = 0;
int nthcounter = 0;
while (nthcounter != n) //when total prime number equal to 10000, stop loop
{
if(isPrime(i) == true)
{
nthcounter++;
}
i++;
}
return i;
}
you should return i instead of nthcounter
your while loop check and return value have problems.
public class AnalyzingPrime
{
public static boolean isPrime (int n)
{
if (n==1)
return false;
for (int i = 2; i < n; i++)
{
if (n%i==0)
return false;
}
return true;
}
public static void main (String [] args)
{
int numberofPrimes = 0;
int counter = 0;
int number = 10000;
//add the variable to control which prime number you want
int primeCount = 4;
for (int i = 2; i <= number; i++)
{
if (isPrime(i) == true)
{
counter++;
}
}
System.out.println("There are "+counter+" prime numbers.");
System.out.println("And if you care, the " + primeCount + "th prime number is "+ nthPrime(primeCount)+".");
}
public static int nthPrime (int n)
{
//if you know 1 is not prime number then why start with 0
int i = 1;
int nthcounter = 0;
//should not be <= but < because when equal should not go inside the while loop
while (nthcounter < n)
{
i++;
if(isPrime(i) == true)
{
nthcounter++;
}
}
//should not return the counter but the prime value you want
return i;
}
}

Powers of 10 generator (Cannot find variable i)

I am working on the "Powers of" generator and I get an error that variable i cannot be found. I clearly declared it in the for loop
public class EP63
{
private static int answer;
public static int PowerGenerator(double aFactor)
{
for(int i = 1; i < 12; i++);
{
answer = Math.pow(aFactor,i);
nextPower();
return answer;
}
}
public static double nextPower()
{
System.out.println(answer);
}
}
Can someone explain to me how to fix this problem?
It's this line:
for(int i = 1; i < 12; i++);
Change to:
for(int i = 1; i < 12; i++)
The body of the for loop is a single expression. ; is interpreted as an no-op expression, so the { } block is not part of the loop, therefore i is not defined there.
Because you have a ; after the for loop.
That means the for loop have only 1 empty statement.
i.e. your code is just the same as
for(int i = 1; i < 12; i++) {
// nothing
}
{
answer = Math.pow(aFactor,i);
nextPower();
return answer;
}

Categories