How to resolve the algorithm Additive primes step by step in the Processing programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Additive primes step by step in the Processing programming language

Table of Contents

Problem Statement

In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes.

Write a program to determine (and show here) all additive primes less than 500. Optionally, show the number of additive primes.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Additive primes step by step in the Processing programming language

Source code in the processing programming language

IntList primes = new IntList();

void setup() {
  sieve(500);
  int count = 0;
  for (int i = 2; i < 500; i++) {
    if (primes.hasValue(i) && primes.hasValue(sumDigits(i))) {
      print(i + " ");
      count++;
    }
  }
  println();
  print("Number of additive primes less than 500: " + count);
}

int sumDigits(int n) {
  int sum = 0;
  for (int i = 0; i <= floor(log(n) / log(10)); i++) {
    sum += floor(n / pow(10, i)) % 10;
  }
  return sum;
}

void sieve(int max) {
  for (int i = 2; i <= max; i++) {
    primes.append(i);
  }
  for (int i = 0; i < primes.size(); i++) {
    for (int j = i + 1; j < primes.size(); j++) {
      if (primes.get(j) % primes.get(i) == 0) {
        primes.remove(j);
        j--;
      }
    }
  }
}

  

You may also check:How to resolve the algorithm Polyspiral step by step in the Processing programming language
You may also check:How to resolve the algorithm Color wheel step by step in the Processing programming language
You may also check:How to resolve the algorithm Draw a cuboid step by step in the Processing programming language
You may also check:How to resolve the algorithm N-queens problem step by step in the Processing programming language
You may also check:How to resolve the algorithm Archimedean spiral step by step in the Processing programming language