1

How do I check if a given number is prime in twig?

  • 1
    I'm curious about the use case you want to implement this, nicael. – carlcs Jul 10 '14 at 16:12
  • @Christian Well... I'll think :D – nicael Jul 10 '14 at 16:40
2

Example using build-in functions (sure, not the best ;-) ).

Supposing that number is our number:

{% set result = 0 %}
{% if number / number|round == 1 %}
    {% set result = 1 %}
    {% if number > 3 %}
        {% for i in 2..number-1 if result == 1 %}
            {% if number is divisibleby(i) %}
                {% set result = 2 %}
            {% endif %}
        {% endfor %}
    {% endif %}
{% endif %}

Now, result equals to:

  • 0, if number is not integer

  • 1, if number is prime

  • 2, if number is composite

  • en.wikipedia.org/wiki/Prime_number – carlcs Jul 10 '14 at 15:19
  • Also: if result == 1 in line 4 makes no sense – carlcs Jul 10 '14 at 15:21
  • 1
    @Christian I have already read about prime number (what am I missing?). And line 4 is valid. Not sure what is wrong. – nicael Jul 10 '14 at 15:30
  • Sorry nicael, I overlooked that you are overwriting the result var if your number is a composite. Only read this: {% if number / number|round == 1 %}{% set result = 1 %} and immediately the word integer came to mind. – carlcs Jul 10 '14 at 15:47
  • @Christian Yes, it does )) So what? Some simpler check which I don't know about? – nicael Jul 10 '14 at 15:57
1

I think the question of the use-case is vital here. If you want to check whether a large number is prime or not, you will need a plugin and a lot of math.

If your number is guaranteed not too big, I would use twig's in operator:

{% set primes = [2, 3, 5, 6, 11, 13, 17, 19] %}
{% if n > primes|last %}
  too big to tell
{% elseif n in primes %}
  {{n}} is prime
{% else %}
  {{n}} is composite
{% endif %}

Or check for prime factors in a loop:

{% set primes = [2, 3, 5, 6, 11, 13, 17, 19] %}
{% if n > (primes|last) * (primes|last) %}
  too big to tell
{% else %}
  {% set isComposite = false %}
  {% for p in primes %}
    {% if (not isComposite) and  (n is divisibleby (p)) %}
      {{n}} is composite (divisible by {{p}})
      {% set isComposite = true %}
      {# optional break #}
    {% endif %}
  {% endfor %}
  {% if not isComposite %}
    {{n}} is prime
  {% endif %}
{% endif %}

(Twig doesn't have a native break tag, but you can use a plugin)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.