+ 1

how do i improve this code for prime numbers calculation?

the code: https://code.sololearn.com/ca1198A25a15/#java hi, I started studying java for a week and it is the first language I learn, so I'm sure that there will be errors in this code or that there is a faster and more efficient way to do the same thing, but I wanted do it on my own without asking for help or copying someone else's code! I have tried to cover all possible bugs such as negative numbers or inverted ranges and have excluded -1 and 1 as they are not considered prime numbers. in theory the program also calculates huge numbers but with times that grow exponentially. beyond a certain limit you will receive the "execution timeout" error because the required computing power is too high. by starting the program locally you can calculate any number! but it took my Ryzen 2600 at 4.1Ghz 10 minutes at 70° to calculate prime numbers only between 100'000'000'000 and 100'000'000'100 (there are 7 prime numbers in the range) I tried to increase the efficiency by calculating only odd numbers, breaking the loop as soon as it turns out that the number is not prime without calculating all the other possibilities and the same thing I did for when it turns out that the number is prime, so when the result of division is less than 3 and no integer results have been found yet. I know there are much more efficient methods but I wanted to write the program as an exercise without taking any suggestions from the web but now that I have finished the program and loaded it, I would be curious to know if I made mistakes, if the same code could be written in a more synthetic way and how the calculation can be made more efficient! anyone want to give me some suggestions? thank you!

13th Mar 2021, 7:41 PM
Alessandro Bellina
Alessandro Bellina - avatar
3 Respuestas
+ 2
I am not going through your code but one of the most of optimized way to do is as following (it is in python), def prime_number(num): assert num>1,"num should be equal to or greater than 1" # assert checks if "num>1" is true or not ,if not true it will print the string following it and code execution stops. if(num==2 or num==3): return True elif(num%2==0 or num%3==0): return False i=5 while(i*i<=num): if(num%i==0 or num%(i+2)==0): return False i+=6 return True for i in range(100000000000,100000000100): print(prime_number(i)) Shudn't be hard to understand ,"elif" is "if else " In java. If something doesn't makes sense let me know. The above code was executed in 1.24 seconds on a mediatek helio G35 2.3ghz processor.
13th Mar 2021, 9:07 PM
Abhay
Abhay - avatar
+ 1
Hi Alessandro Bellina. You can use various algorithms for printing the number of prime numbers between two longs. One of the most common of these is the Sieve Of Eratosthenes. https://code.sololearn.com/cSY3Xs616wPe/?ref=app
14th Mar 2021, 3:34 AM
Soumik
Soumik - avatar