Java - Quick modulus operation -


i want this:

public int myfunc(int n) {     for(int i=0; i<=n; i++)     {         if(n % == 0)             return i;     }         return 0; } 

with small numbers, works fine, on greater ones not. how can accomplish same thing, without % operator?

thank you.

sadly cannot quickly.

the fastest way - int being used - run through list of known primes checking divisibility.

here list of first 1000 primes. read them in , try each in turn sqrt(n).

something this:

// 10,000 primes - http://primes.utm.edu/lists/small/10000.txt private static final arraylist<integer> someprimes = new arraylist<>(); private static final string primesfilename = "10000primes.txt"; //private static final string primesfilename = "100008primes.txt";  static {   try (inputstream in = primes.class.getresourceasstream(primesfilename);           inputstreamreader isr = new inputstreamreader(in);           bufferedreader br = new bufferedreader(isr)) {     (string s; br.ready() && (s = br.readline()) != null;) {       // split commas.       string[] ps = s.split(",");       (string p : ps) {         if (p.length() > 0) {           someprimes.add(integer.valueof(p));         }       }     }   } catch (ioexception ex) {     system.err.println("loading pf primes failed.");     ex.printstacktrace(system.err);   }   //system.out.println("primes: "+someprimes.size()); }  public static boolean isprime(int n) {   if (n <= 2) {     return true;   }   int limit = (int) math.round(math.sqrt(n));   (integer p : someprimes) {     if (p <= limit) {       if ((n % p) == 0) {         return false;       }     } else {       return true;     }   }   return true; } 

Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -