Math Flashcards

1
Q

Prime numbers upto a given n

A

it is safe to assume that all n^2 and n^ +n, n^2 +n + n can be set to non prime. Take an example of 2 –> 4, 6, 8 all are multiples of 2 so not prime.

the for (int i = 2; i * i < n; i++) is because if we need to find primes till n, then we only need to care if there are 4, 8 etc in the order till n

public int countPrimes(int n) {
   boolean[] isPrime = new boolean[n];
   for (int i = 2; i < n; i++) {
      isPrime[i] = true;
   }
   // Loop's ending condition is i * i < n instead of i < sqrt(n)
   // to avoid repeatedly calling an expensive function sqrt().
   for (int i = 2; i * i < n; i++) {
      if (!isPrime[i]) continue;
      for (int j = i * i; j < n; j += i) {
         isPrime[j] = false;
      }
   }
   int count = 0;
   for (int i = 2; i < n; i++) {
      if (isPrime[i]) count++;
   }
   return count;
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How to determine a number is a fraction or not?

A

Modulo the number n % 1. If it is equal to 0 then it is a whole number, else its a fraction

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How to find if a given number is divisible by a power of n?

A
  1. Then x% n == 0 for every x=x/n;
  2. Another option is Math.log(x)/ Math.log(n) % 1 (to see its not a decimal) == 0

Example check if x is a power of 3(n)
then 3^i = x then i=logx/log3

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Some basic operations for conversions

A
  1. int to String : Integer.toString(i) or String.valueOf(i)

2. String to int. Integer.parseInt(s)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly