- 5
Please I need a detailed code that will list all the prime numbers between 1&100
Java
8 Respuestas
+ 6
How about you make the code yourself?
+ 4
Then why don't you go to the playground and search for "prime" with Java as language? You'll find plenty of reference there to code what you want, and if you still have questions about errors, the logic or whatever, you can come back here. Please don't expect others to do your work.
+ 1
I never actually learned Java, luckily the syntax is not very different to C++. Okay, first, the idea is that a number is prime if it has exactly two divisors (which would always be 1 and itself).
"primeNumbers" is a string we are going to fill with the primes we find, while "i" represents the number we are currently testing.
"counter" counts how often a number could be fully divided.
Now we test for each number from "i" to 1 (inner for-loop) if it is a divisor of "i" by using the modulo. If the number is a divisor, we increase the counter by one.
After we are done with that, we apply our idea from the beginning. If "i" has exactly 2 divisors (counter == 2), the number must be prime, so we add it at the end of primeStrings, otherwise the number is not a prime and we move on to the next "i".
At the end, we simply output our string holding all the prime numbers.
+ 1
I did a code on that a while back. For curiousity and testing purposes.
https://code.sololearn.com/ctmUeISSLs25/?ref=app
+ 1
Thanks a lot @Naitomea
I appreciate your help
+ 1
Thanks Andre Daniel
0
class PrimeNumbers { public static void main (String[] args) { int i =0; int num =0; //Empty String String primeNumbers = ""; for (i = 1; i <= 100; i++) { int counter=0; for(num =i; num>=1; num--) { if(i%num==0) { counter = counter + 1; } } if (counter ==2) { //Appended the Prime number to the String primeNumbers = primeNumbers + i + " "; } } System.out.println("Prime numbers from 1 to 100 are :"); System.out.println(primeNumbers); }
0
Actually, I wanted to do the prime number project to improve myself personally, but I didn't just know how to go about it.
Then I got the above code from Google but still don't understand.
I'll appreciate if you can explain the code above.