Home / Technical / Programming / Algorithm / Mathematics for Programming

Mathematics for Programming

Mathematics for programming

Reference

To  check whether a number is prime:

public boolean isPrime (int n) {
   if (n<=1) return false;
   if (n==2) return true;
   if (n%2==0) return false;
   int m=Math.sqrt(n);
   for (int i=3; i<=m; i+=2)
      if (n%i==0)
         return false;
   return true;
}
----------------------------------------------
+ To find all the primes from 1 to n: (using the Sieve of Eratosthenes Method)

public boolean[] sieve(int n) {
   boolean[] prime=new boolean[n+1];
   Arrays.fill(prime,true);
   prime[0]=false;
   prime[1]=false;
   int m=Math.sqrt(n);
   for (int i=2; i<=m; i++)
      if (prime[i])
         for (int k=i*i; k<=n; k+=i)
            prime[k]=false;
   return prime;
}

About Mohammad Khazab

Leave a Reply

%d bloggers like this: