DEV Community

Cover image for Pure CSS prime calculation
owieczka
owieczka

Posted on

Pure CSS prime calculation

Use CSS selector power to calculate Primes

You probably didn't know that pure CSS can be used to calculate prime numbers. Prime numbers are such a numbers that divided only by 1 and itself.

Normaly we can compute primes by Sieve of Eratosthenes. It's a clever algorytm invented by Greeks 3rd cent BCE. You starts with list of all numbers. In HTML we can create list of all numbers with help of CSS counters and i element.

<div class="container">
  <i></i><i></i><i></i><i></i><i></i>
  <i></i><i></i><i></i><i></i><i></i>
  <i></i><i></i><i></i><i></i><i></i>
  <i></i><i></i><i></i><i></i><i></i>
  <i></i><i></i><i></i><i></i><i></i>
  <i></i><i></i><i></i><i></i><i></i>
  <i></i><i></i><i></i><i></i><i></i>
  <i></i><i></i><i></i><i></i><i></i>
  <i></i><i></i><i></i><i></i><i></i>
  <i></i><i></i><i></i><i></i><i></i>
  <i></i><i></i><i></i><i></i><i></i>
  <i></i><i></i><i></i><i></i><i></i>
  <i></i><i></i><i></i><i></i><i></i>
  <i></i><i></i><i></i><i></i><i></i>
  <i></i><i></i><i></i><i></i><i></i>
  <i></i><i></i><i></i><i></i><i></i>
  <i></i><i></i><i></i><i></i><i></i>
  <i></i><i></i><i></i><i></i><i></i>
  <i></i><i></i><i></i><i></i><i></i>
  <i></i><i></i><i></i><i></i><i></i>
</div>
Enter fullscreen mode Exit fullscreen mode
.container {
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
  align-items: flex-start;
  align-content: flex-start;
  counter-reset: i_counter; 
}

.container i {
  display: flex;
  align-items: center;
  align-content: center;
  justify-content: center;
  transition: 
    width 2s ease-out,
    background-color 0.2s ease-out;
  width: 2.0rem;
  height: 2.0rem;
  border-radius: 5px;
  border: 1px solid hsl(45 0% 90%);
  box-shadow: 4px 4px 8px -4px rgba(66, 68, 90, 1);
  overflow: hidden;
  font-style: normal;
}

.container i:before {
  counter-increment: i_counter;
  content: counter(i_counter);
}
Enter fullscreen mode Exit fullscreen mode

Step two is to remove all composite numbers. We can use CSS selectors :nth-child to remove all multiplication of a given number. But we must keep 0th element of a series. We can do it with :is and :not selectors.

.container :is(
i:nth-child(0n+1),
i:nth-child(2n):is(:not(i:nth-child(0n+2))),
i:nth-child(3n):is(:not(i:nth-child(0n+3))),
i:nth-child(4n):is(:not(i:nth-child(0n+4))),
i:nth-child(5n):is(:not(i:nth-child(0n+5))),
i:nth-child(6n):is(:not(i:nth-child(0n+6))),
i:nth-child(7n):is(:not(i:nth-child(0n+7))),
i:nth-child(8n):is(:not(i:nth-child(0n+8))),
i:nth-child(9n):is(:not(i:nth-child(0n+9))),
i:nth-child(10n):is(:not(i:nth-child(0n+10))),
)
{
  width: 10px;
  background-color: hsl(0 60% 90%);
  /*display: none;*/
  font-size: 0.5rem;
}
Enter fullscreen mode Exit fullscreen mode

For finding all primes up to 100 it is sufficient to remove all multiplicative of a numbers from 1 to 10.

Full solution - on Codepen

Top comments (0)