+ 3

How to find largest prime no?

6th Feb 2017, 4:17 PM
SHASHI
SHASHI - avatar
6 odpowiedzi
+ 9
// Short.MAX_VALUE was chosen as an example. // Use anything from 2 to Long.MAX_VALUE instead, although // SoloLearn may want to interrupt the program by timeout. public class LargestPrimeNumber { public static void main(String[] args) { long i, max = Short.MAX_VALUE; boolean prime = false; for (i = max; i > 2; i--) { for (long j = 2; j < i; j++) { prime = i % j == 0 ? false : true; if (!prime) break; } if (prime) break; } System.out.print(i); } } Here is a quick link to tinker with the code: https://code.sololearn.com/c714Nc9x4XnO/#java How far can you actually get? According to The Java® Language Specification (Java SE 8 Edition), it is possible to get far enough. 4.2.1. Integral Types and Values The values of the integral types are integers in the following ranges: For byte, from -128 to 127, inclusive For short, from -32768 to 32767, inclusive For int, from -2147483648 to 2147483647, inclusive For long, from -9223372036854775808 to 9223372036854775807, inclusive For char, from '\u0000' to '\uffff' inclusive, that is, from 0 to 65535 Just in case you'd like to play with REALLY big numbers, there is always a few voodoo spells to get beyond the limits. Feel free to ask in case you're interested.
6th Feb 2017, 7:23 PM
Maxim Remyga
Maxim Remyga - avatar
+ 8
@James Durand, sometimes it is necessary to read between the lines (also known as guessing) to better understand the question. It is quite natural to assume that the asker is good enough in math to know for sure that there is no 'the largest prime' in general. At the same time, he might be wondering what is the largest prime that can actually fit into Java built-in primitive integer types.
6th Feb 2017, 5:34 PM
Maxim Remyga
Maxim Remyga - avatar
+ 5
There is no largest prime number. The primes are an infinite set. You can find large ones but not the largest.
6th Feb 2017, 4:19 PM
James Durand
James Durand - avatar
+ 2
@Max Rem, those are the largest built in primitive integers. That wouldn't give you the largest prime number. You can get numbers larger than the primitives support in Java using other types.
6th Feb 2017, 4:28 PM
James Durand
James Durand - avatar
0
o really, thank you
6th Feb 2017, 4:21 PM
SHASHI
SHASHI - avatar
0
说的什么
24th Apr 2017, 3:02 PM
Java