my friend(who is better than me in codding) and I are working on a university homework, but before I get to the point I want to mention that I'm no expert and a total noob in comparison to you guys. (2-weeks coding journey). he had an operation and can't help me so I'm by my own that's why I'm writing here to get some help.
okay, that being said lets hit to the point. the exercise is to make an Eratosthenes-sieve without any multiplication, division nor for loops. Now the problem is that I've written before the professor tell us not to use those things and now I don't know what to do. changing the for loops to while is no big deal but I have no clue how to get rid of the last multiplication at the end of the code.
so I wrote the code and sent it to my fellow he did some changes that I didn't well understand //I will comment on the changes that he did and I would be really thankful if someone did explain some point for me.
1)so first we need to get rid of the for loops and replace it with while which is no big deal and then get rid of the multiplication at the end of the code which is my main problem.
2)help to understand some points.
import java.util.Scanner; public class primesieb { public static void main(String[] args) { //so we declare values and used the scanner to make an input. int input = 0; Scanner in = new Scanner(System.in); System.out.println("give an int bigger that 1: "); input = in.nextInt(); while (input <= 1) { //in case the number is smaller than 1. System.out.println("the Int must be bigger than 1!."); System.out.println("write an Int bigger than 1: "); input = in.nextInt(); } in.close(); //now first i wrote it without "+1" but my friend changed it to +1 boolean[] x = new boolean[input + 1]; //here I just wanted to add this to set that the position 0 in the string is not a prime number but after thinking I don't see its necessary x[0]=false; //he did write this commented for loop to assume that all of them are false but for me, it doesn't make sense, pls explain if it's necessary. //for (int i = 2; i < x.length; i++) { // x[i] = false;} for (int i = 2; i < x.length; i++) { while (x[i]) { i++; } // here how can we get rid of the multiplication. //the next for loop and if my friend did and a better explain would be nice helping me to represent my code better. for (int j = i; j*i < input; j++) { x[i * j] = true; } if (! x[i] && i < input) { System.out.println("the number" + i + "is prime. "); } } } }
NOTE I tried now to use the (int)Math.sqrt(i) and I got an ErrorI have no idea what is this.Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 11 at primesiebselber.main(primesiebselber.java:31)
and i did try thisbut the code is showing nothing after my input!!!for (int j = i, z= (int)Math.pow (i,j); z < eingabe; j++) { x[z] = true;}