Jump to content

Sum of square and cube digits of an integer are primes

From Rosetta Code
Sum of square and cube digits of an integer are primes is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.
Task

Find and show here all positive integers n less than 100 where:

  • the sum of the digits of the square of n is prime; and
  • the sum of the digits of the cube of n is also prime.


Example

16 satisfies the task descrption because 16 x 16 = 256 has a digit sum of 13 which is prime and 16 x 16 x 16 = 4096 has a digit sum of 19 which is also prime.

ABC

HOW TO REPORT prime n:
    REPORT n>=2 AND NO d IN {2..floor (root n)} HAS n mod d=0

HOW TO RETURN digit.sum n:
    SELECT:
        n < 10: RETURN n
        ELSE: RETURN (n mod 10) + digit.sum (floor (n / 10))

FOR n IN {1..99}:
    IF prime (digit.sum (n**2)) AND prime (digit.sum (n**3)):
        WRITE n/
Output:
16
17
25
28
34
37
47
52
64

Ada

-- Rosetta Code Task written in Ada
-- Sum of square and cube digits of an integer are primes
-- https://rosettacode.org/wiki/Sum_of_square_and_cube_digits_of_an_integer_are_primes
-- Loosely translated from the Nim solution
-- March 2025, R. B. E.

with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;

procedure Sum_of_Square_and_Cube_Digits_of_an_Integer_are_Primes is

  function Is_Prime (Candidate : in Positive) return Boolean is
    type Prime_Sieve_Array is array (Positive range <>) of Positive;
    Prime_Sieve : Prime_Sieve_Array := (2, 3, 5, 7, 11, 13, 17, 19);
  begin
    for J in Prime_Sieve'Range loop
      if Candidate = Prime_Sieve (J) then
        return True;
      end if;
    end loop;
    return False;
  end Is_Prime;

  function Sum_of_Digits (N : in Positive) return Positive is
    Local_N : Natural := N;
    Result : Natural := 0;
  begin
    while Local_N > 0 loop
      Result := Result + Local_N mod 10;
      Local_N := Local_N / 10;
    end loop;
    return Result;
  end Sum_of_Digits;

  N_Squared, N_Cubed : Positive;
  Sum_of_the_Squared_Digits : Positive;
  Sum_of_the_Cubed_Digits : Positive;

begin
  for I in 5..99 loop
    N_Squared := I * I;
    N_Cubed := N_Squared * I;
    Sum_of_the_Squared_Digits := Sum_of_Digits (N_Squared);
    Sum_of_the_Cubed_Digits := Sum_of_Digits (N_Cubed);
    if ((Is_Prime (Sum_of_Digits (N_Squared))) and (Is_Prime (Sum_of_Digits (N_Cubed)))) then
      Put (I, 0);
      Put (" ");
    end if;
  end loop;
  New_Line;
end Sum_of_Square_and_Cube_Digits_of_an_Integer_are_Primes;
Output:
16 17 25 28 34 37 47 52 64

ALGOL 68

BEGIN # find numbers where the digit sums of the square and cube are prime #
    INT max number = 99; # maximum number to consider #
    PR read "primes.incl.a68" PR
    []BOOL prime = PRIMESIEVE ( INT d sum := 9; # calculate the largest possible digit sum #
                                INT n     := max number * max number * max number;
                                WHILE ( n OVERAB 10 ) > 0 DO
                                    d sum +:= 9
                                OD;
                                d sum
                              );
    # returns the sum of the digits of n #
    OP  DIGITSUM = ( INT n )INT:
        BEGIN
            INT v      := ABS n;
            INT result := v MOD 10;
            WHILE ( v OVERAB 10 ) > 0 DO
                result +:= v MOD 10
            OD;
            result
        END # DIGITSUM # ;
    FOR i TO max number DO
        INT i2 = i * i;
        IF prime[ DIGITSUM i2 ] THEN
            IF prime[ DIGITSUM ( i * i2 ) ] THEN
                print( ( " ", whole( i, 0 ) ) )
            FI
        FI
    OD
END
Output:
 16 17 25 28 34 37 47 52 64

ALGOL W

begin
    integer procedure digitSum( integer value n ) ;
    begin
        integer sum, v, vOver10;
        sum := 0;
        v   := n;
        while v > 0 do begin
            vover10 := v div 10;
            sum     := sum + ( v - ( vover10 * 10 ) );
            v       := vover10
        end while_v_gt_0 ;
        sum
    end digitSum ;
    logical procedure isPrime( integer value n ) ;
        if      n < 2        then false
        else if not odd( n ) then n = 2
        else begin
            logical prime;
            integer p;
            prime := true;
            p     := 3;
            while p * p <= n and prime do begin
               prime := n rem p not = 0;
               p := p + 2;
            end while_p2_le_n_and_prime ;
            prime
        end isPrime ;
    for i := 1 until 99 do begin
        integer i2;
        i2 := i * i;
        if isPrime( digitSum( i2 ) ) then begin;
            if isPrime( digitSum( i2 * i ) ) then writeon( i_w := 1, s_w := 1, i )
        end
    end
end.
Output:
16 17 25 28 34 37 47 52 64

APL

((/⍨)/∘((2=0+.=⍳|⊢)(+/¨∘)¨*2 3)¨)100
Output:
16 17 25 28 34 37 47 52 64

Arturo

print select 1..100 'x ->
    and? [prime? sum digits x^2]
         [prime? sum digits x^3]
Output:
16 17 25 28 34 37 47 52 64

AWK

# syntax: GAWK -f SUM_OF_SQUARE_AND_CUBE_DIGITS_OF_AN_INTEGER_ARE_PRIMES.AWK
# converted from FreeBASIC
BEGIN {
    start = 1
    stop = 99
    for (i=start; i<=stop; i++) {
      if (is_prime(digit_sum(i^3,10)) && is_prime(digit_sum(i^2,10))) {
        printf("%5d%1s",i,++count%10?"":"\n")
      }
    }
    printf("\nSum of square and cube digits are prime %d-%d: %d\n",start,stop,count)
    exit(0)
}
function digit_sum(n,b,  s) { # digital sum of n in base b
    while (n) {
      s += n % b
      n = int(n/b)
    }
    return(s)
}
function is_prime(n,  d) {
    d = 5
    if (n < 2) { return(0) }
    if (n % 2 == 0) { return(n == 2) }
    if (n % 3 == 0) { return(n == 3) }
    while (d*d <= n) {
      if (n % d == 0) { return(0) }
      d += 2
      if (n % d == 0) { return(0) }
      d += 4
    }
    return(1)
}
Output:
   16    17    25    28    34    37    47    52    64
Sum of square and cube digits are prime 1-99: 9

BASIC

ANSI BASIC

Translation of: XPL0
Works with: Decimal BASIC
100 REM Sum of square and cube digits of an integer are primes
110 DECLARE EXTERNAL FUNCTION SumDigits
120 DECLARE EXTERNAL FUNCTION IsPrime
130 FOR N = 0 TO 99
140    IF IsPrime(SumDigits(N * N)) <> 0 AND IsPrime(SumDigits(N * N * N)) <> 0 THEN PRINT N;
150 NEXT N
160 PRINT
170 END
180 REM **
190 EXTERNAL  FUNCTION IsPrime (Num)
200 IF Num < 2 THEN
210    LET IsPrime = 0
220    EXIT FUNCTION
230 END IF
240 IF Num = 2 THEN
250    LET IsPrime = -1
260    EXIT FUNCTION
270 END IF
280 IF MOD(Num, 2) = 0 THEN
290    LET IsPrime = 0
300    EXIT FUNCTION
310 END IF
320 LET I = 3
330 DO WHILE I * I <= Num
340    IF MOD(Num, I) = 0 THEN 
350       LET IsPrime = 0
360       EXIT FUNCTION
370    END IF
380    LET I = I + 2
390 LOOP
400 LET IsPrime = -1  
410 END FUNCTION
420 REM **
430 EXTERNAL FUNCTION SumDigits(Num)
440 LET Sum = 0
450 DO WHILE Num <> 0
460    LET Sum = Sum + MOD(Num, 10)
470    LET Num = INT(Num / 10)
480 LOOP
490 LET SumDigits = Sum
500 END FUNCTION
Output:
 16  17  25  28  34  37  47  52  64 

ASIC

Works with: ASIC version 5.0

Compile with the option Extended Math (E in command line).

REM Sum of square and cube digits of an integer are primes
FOR N = 1 TO 99
  NumExt& = N * N
  GOSUB SumDigits:
  Num = Sum
  GOSUB CheckIfPrime:
  IF IsPrime = 1 THEN
    NumExt& = NumExt& * N
    GOSUB SumDigits:
    Num = Sum
    GOSUB CheckIfPrime:
    IF IsPrime = 1 THEN
      PRINT N
    ENDIF
  ENDIF
NEXT N
END

SumDigits:
REM Sums digits of NumExt&.
  Sum = 0
  TmpNum& = NumExt&
  REM TmpNum& used in order not to change a value of the "parameter"
  WHILE TmpNum& <> 0
    NumMod10& = TmpNum& MOD 10
    Sum = Sum + NumMod10&
    TmpNum& = TmpNum& / 10
  WEND
RETURN

CheckIfPrime:
REM Checks if Num is prime.
  IF Num < 2 THEN
    IsPrime = 0
  ELSE
    IF Num = 2 THEN
      IsPrime = 1
    ELSE
      NumMod2 = Num MOD 2
      IF NumMod2 = 0 THEN
        IsPrime = 0
      ELSE
        IsPrime = 1
        I = 3
        I2& = I * I
        Hi& = Num * IsPrime
        WHILE I2& <= Hi&
          AModI = Num MOD I
          IF AModI = 0 THEN
            IsPrime = 0
          ENDIF
          I = I + 2
          I2& = I * I
          Hi& = Num * IsPrime
        WEND
      ENDIF
    ENDIF
  ENDIF
RETURN
Output:
    16
    17
    25
    28
    34
    37
    47
    52
    64

FreeBASIC

function digsum(byval n as uinteger, b as const uinteger) as uinteger
    'digital sum of n in base b
    dim as integer s
    while n
        s+=n mod b
        n\=b
    wend
    return s
end function

function isprime(n as const uinteger) as boolean
    if n<2 then return false
    if n<4 then return true
    if n mod 2 = 0 then return false
    dim as uinteger i = 3
    while i*i<=n
        if n mod i = 0 then return false
        i+=2
    wend
    return true
end function

for n as uinteger = 1 to 99
    if isprime(digsum(n^3,10)) andalso isprime(digsum(n^2,10)) then print n;"   ";
next n
Output:
16   17   25   28   34   37   47   52   64

QuickBASIC

Translation of: XPL0
' Sum of square and cube digits of an integer are primes
DECLARE FUNCTION SumDigits% (Num&)
DECLARE FUNCTION IsPrime% (Num%)
CONST TRUE% = -1, FALSE% = 0
FOR N = 0 TO 99
  IF IsPrime%(SumDigits%(N * N)) AND IsPrime%(SumDigits%(N * N * N)) THEN PRINT N;
NEXT N
PRINT
END

FUNCTION IsPrime% (Num%)
  IF Num% < 2 THEN
    IsPrime% = FALSE%
  ELSEIF Num% = 2 THEN
    IsPrime% = TRUE%
  ELSEIF Num% MOD 2 = 0 THEN
    IsPrime% = FALSE%
  ELSE
    I% = 3: FoundFac% = FALSE%
    WHILE I% * I% <= Num% AND NOT FoundFac%
      IF Num% MOD I% = 0 THEN FoundFac% = TRUE%
      I% = I% + 2
    WEND
    IsPrime% = NOT FoundFac%
  END IF
END FUNCTION

FUNCTION SumDigits% (Num&)
  Sum% = 0
  WHILE Num& <> 0
    Sum% = Sum% + Num& MOD 10
    Num& = Num& \ 10
  WEND
  SumDigits% = Sum%
END FUNCTION
Output:
 16  17  25  28  34  37  47  52  64

RapidQ

Translation of: QuickBASIC
' Sum of square and cube digits of an integer are primes
DECLARE FUNCTION SumDigits (Num&) AS SHORT
DECLARE FUNCTION IsPrime (Num%) AS SHORT
CONST TRUE% = -1
CONST FALSE% = 0
FOR N = 0 TO 99
  IF IsPrime(SumDigits(N * N)) AND IsPrime(SumDigits(N * N * N)) THEN PRINT N; " ";
NEXT N
PRINT
END

FUNCTION IsPrime (Num%) AS SHORT
  IF Num% < 2 THEN
    IsPrime = FALSE%
  ELSEIF Num% = 2 THEN
    IsPrime = TRUE%
  ELSEIF Num% MOD 2 = 0 THEN
    IsPrime = FALSE%
  ELSE
    I% = 3: FoundFac% = FALSE%
    WHILE I% * I% <= Num% AND NOT FoundFac%
      IF Num% MOD I% = 0 THEN FoundFac% = TRUE%
      I% = I% + 2
    WEND
    IsPrime = NOT FoundFac%
  END IF
END FUNCTION

FUNCTION SumDigits (Num&) AS SHORT
  Sum% = 0
  WHILE Num& <> 0
    Sum% = Sum% + Num& MOD 10
    Num& = Num& \ 10
  WEND
  SumDigits = Sum%
END FUNCTION
Output:
16 17 25 28 34 37 47 52 64

Tiny BASIC

Works with: TinyBasic

This can only go up to 31 because 32^3 is too big to fit in a signed 16-bit int.

10 REM Sum of square and cube digits of an integer are primes
20 REM N, the number to be tested
30 REM D, the digital sum of its square or cube
40 REM T, temporary variable
50 REM Z, did D test as prime or not
60 LET N = 1
70 LET T = N * N * N
80 GOSUB 200
90 GOSUB 260
100 IF Z = 0 THEN GOTO 160
110 LET T = N * N
120 GOSUB 200
130 GOSUB 260
140 IF Z = 0 THEN GOTO 160
150 PRINT N
160 IF N = 31 THEN END
170 LET N = N + 1
180 GOTO 70
190 REM Calculate sum of digits
200 LET D = 0
210 IF T = 0 THEN RETURN
220 LET D = D + (T - (T / 10) * 10)
230 LET T = T / 10
240 GOTO 210
250 REM Check if is prime
260 LET Z = 0
270 IF D < 2 THEN RETURN
280 LET Z = 1
290 IF D < 4 THEN RETURN
300 LET Z = 0
310 IF (D / 2) * 2 = D THEN RETURN
320 LET T = 1
330 LET T = T + 2
340 IF T * T > D THEN GOTO 370
350 IF (D / T) * T = D THEN RETURN
360 GOTO 330
370 LET Z = 1
380 RETURN
Output:
16

17 25

28

XBasic

Translation of: XPL0
Works with: Windows XBasic
' sum of square and cube digits of an integer are primes
PROGRAM "sumofdigitsetc"

DECLARE FUNCTION Entry ()
INTERNAL FUNCTION SumDigits (num&&)
INTERNAL FUNCTION IsPrime (num&&)

FUNCTION Entry ()
  FOR n@@ = 0 TO 99
    IF IsPrime(SumDigits(n@@ * n@@)) AND IsPrime(SumDigits(n@@ * n@@ * n@@)) THEN PRINT n@@;
  NEXT n@@
  PRINT
END FUNCTION

FUNCTION SumDigits(num&&)
  sum&& = 0
  DO WHILE num&& <> 0
    sum&& = sum&& + num&& MOD 10
    num&& = num&& \ 10
  LOOP
END FUNCTION sum&&

FUNCTION IsPrime (num&&)
  IF num&& < 2 THEN RETURN $$FALSE 
  IF num&& = 2 THEN RETURN $$TRUE
  IF num&& MOD 2 = 0 THEN RETURN $$FALSE
  i&& = 3
  DO WHILE i&& * i&& <= num&&
    IF num&& MOD i&& = 0 THEN RETURN $$FALSE
    i&& = i&& + 2
  LOOP
  RETURN $$TRUE
END FUNCTION
END PROGRAM
Output:
 16 17 25 28 34 37 47 52 64

Yabasic

Translation of: Ring
// Rosetta Code problem: http://rosettacode.org/wiki/Sum_of_square_and_cube_digits_of_an_integer_are_primes
// by Galileo, 04/2022

sub isPrime(n)
	local i
	
	if n < 4 return n >= 2
	for i = 2 to sqrt(n)
		if not mod(n, i) return false
	next
    return true
end sub
 
limit = 100
 
for n = 1 to limit
    sums = 0
    sumc = 0
    sps$ = str$(n^2)
    spc$ = str$(n^3)
    for m = 1 to len(sps$)
        sums = sums + val(mid$(sps$, m, 1))
    next
    for p = 1 to len(spc$)
        sumc = sumc + val(mid$(spc$, p, 1))
    next
    if isPrime(sums) and isPrime(sumc) then
       print n, " ";
    endif
next
print
Output:
16 17 25 28 34 37 47 52 64
---Program done, press RETURN---

BQN

# 'Library' functions from BQNCrate
Digits  10 {𝕗|⌊÷𝕗(1+·𝕗1⌈⊢)}
Prime  2=·+´0=(1+↕)|

(˝((Prime +´Digits)¨23))/↕100
Output:
⟨ 16 17 25 28 34 37 47 52 64 ⟩

C

#include <stdio.h>
#include <stdbool.h>

int digit_sum(int n) {
    int sum;
    for (sum = 0; n; n /= 10) sum += n % 10;
    return sum;
}

/* The numbers involved are tiny */
bool prime(int n) {
    if (n<4) return n>=2;
    for (int d=2; d*d <= n; d++)
        if (n%d == 0) return false;
    return true;
}

int main() {
    for (int i=1; i<100; i++)
        if (prime(digit_sum(i*i)) & prime(digit_sum(i*i*i)))
            printf("%d ", i);
    printf("\n");
    return 0;
}
Output:
16 17 25 28 34 37 47 52 64

C#

Translation of: XPL0
// Sum of square and cube digits of an integer are primes
using System;

public class SumOfEtc
{
    static bool IsPrime(int num)
    {
        if (num < 2)
            return false;
        if (num == 2)
            return true;
        if (num % 2 == 0)
            return false;
        for (int i = 3; i * i <= num; i += 2)
            if (num % i == 0)
                return false;
        return true;
    }

    static int SumDigits(int num)
    {
        int sum = 0;
        while (num != 0)
        {
            sum += num % 10;
            num /= 10;
        }
        return sum;
    }

    public static void Main(string[] args)
    {
        for (int n = 0; n <= 99; n++)
            if (IsPrime(SumDigits(n * n)) && IsPrime(SumDigits(n * n * n)))
                Console.Write(n + " ");
        Console.WriteLine();
    }
}
Output:
16 17 25 28 34 37 47 52 64

C++

#include <cstdint>
#include <iostream>

bool is_prime(const int32_t& number) {
	if ( number < 2 || ( number & 1 ) == 0 ) {
		return number == 2;
	}

	for ( int32_t i = 3; i * i <= number; i += 2 ) {
		if ( number % i == 0 ) {
			return false;
		}
	}
	return true;
}

int32_t digit_sum(int32_t number) {
	int32_t sum = 0;
	while ( number > 0 ) {
		sum += number % 10;
		number /= 10;
	}
	return sum;
}

int main() {
	for ( uint32_t n = 1; n < 100; ++n ) {
		if ( is_prime(digit_sum(n * n)) && is_prime(digit_sum(n * n * n)) ) {
			std::cout << n << " ";
		}
	}
	std::cout << std::endl;
}
Output:
16 17 25 28 34 37 47 52 64

CLU

digit_sum = proc (n: int) returns (int)
    sum: int := 0
    while n>0 do
        sum := sum + n // 10
        n := n / 10
    end
    return(sum)
end digit_sum

% The numbers tested for primality are very small,
% so this simple test suffices.
prime = proc (n: int) returns (bool)
    if n<2 then return(false) end
    d: int := 2
    while d*d <= n do
        if n//d=0 then return(false) end
        d := d+1
    end
    return(true)
end prime

accept = proc (n: int) returns (bool)
    return(prime(digit_sum(n**2)) cand prime(digit_sum(n**3)))
end accept

start_up = proc ()
    po: stream := stream$primary_output()
    for i: int in int$from_to(1, 99) do
        if accept(i) then
            stream$puts(po, int$unparse(i) || " ")
        end
    end
end start_up
Output:
16 17 25 28 34 37 47 52 64

COBOL

       IDENTIFICATION DIVISION.
       PROGRAM-ID. SQUARE-CUBE-DIGITS-PRIME.
       
       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01 NUMBER-SEARCH-VARS.
          03 CAND             PIC 9(6).
          03 SQUARE           PIC 9(6).
          03 CUBE             PIC 9(6).
          
       01 SUM-DIGITS-VARS.
          03 SUM-NUM          PIC 9(6).
          03 DIGITS           PIC 9 OCCURS 6 TIMES INDEXED BY D
                              REDEFINES SUM-NUM.
          03 SUM              PIC 99.
       
       01 PRIME-TEST-VARS.
          03 DIVISOR          PIC 99.
          03 DIV-TEST         PIC 99V9999.
          03 FILLER           REDEFINES DIV-TEST.
             05 FILLER        PIC 99.
             05 FILLER        PIC 9999.
                88 DIVISIBLE  VALUE ZERO.
          03 PRIME-FLAG       PIC X.
             88 PRIME         VALUE '*'.
       
       01 OUT-FMT             PIC Z9.
       
       PROCEDURE DIVISION.
       BEGIN.
           PERFORM CHECK-NUMBER VARYING CAND FROM 1 BY 1
           UNTIL CAND IS EQUAL TO 100.
           STOP RUN.
       
       CHECK-NUMBER.
           MULTIPLY CAND BY CAND GIVING SQUARE.
           MULTIPLY CAND BY SQUARE GIVING CUBE.
           MOVE SQUARE TO SUM-NUM.
           PERFORM SUM-DIGITS.
           PERFORM PRIME-TEST.
           IF PRIME,
               MOVE CUBE TO SUM-NUM,
               PERFORM SUM-DIGITS,
               PERFORM PRIME-TEST,
               IF PRIME,
                   MOVE CAND TO OUT-FMT,
                   DISPLAY OUT-FMT.
           
       SUM-DIGITS.
           MOVE ZERO TO SUM.
           PERFORM SUM-DIGIT VARYING D FROM 1 BY 1
           UNTIL D IS GREATER THAN 6.
           
       SUM-DIGIT.
           ADD DIGITS(D) TO SUM.
       
       PRIME-TEST.
           MOVE '*' TO PRIME-FLAG.
           PERFORM CHECK-DIVISOR VARYING DIVISOR FROM 2 BY 1
           UNTIL NOT PRIME, OR DIVISOR IS EQUAL TO SUM.
       
       CHECK-DIVISOR.
           DIVIDE SUM BY DIVISOR GIVING DIV-TEST.
           IF DIVISIBLE, MOVE SPACE TO PRIME-FLAG.
Output:
16
17
25
28
34
37
47
52
64

Cowgol

include "cowgol.coh";

sub prime(n: uint32): (p: uint8) is
    if n < 2 then
        p := 0;
        return;
    end if;
    p := 1;
    var d: uint32 := 2;
    while d*d <= n loop
        if n%d == 0 then
            p := 0;
            return;
        end if;
        d := d + 1;
    end loop;
end sub;

sub digit_sum(n: uint32): (ds: uint32) is
    ds := 0;
    while n > 0 loop
        ds := ds + n % 10;
        n := n / 10;
    end loop;
end sub;

var n: uint32 := 1;
while n < 100 loop
    if prime(digit_sum(n*n)) != 0 and prime(digit_sum(n*n*n)) != 0 then
        print_i32(n);
        print_nl();
    end if;
    n := n + 1;
end loop;
Output:
16
17
25
28
34
37
47
52
64

Delphi

Works with: Delphi version 6.0


procedure GetDigits(N: integer; var IA: TIntegerDynArray);
{Get an array of the integers in a number}
{Numbers returned from least to most significant}
var T,I,DC: integer;
begin
DC:=Trunc(Log10(N))+1;
SetLength(IA,DC);
for I:=0 to DC-1 do
	begin
	T:=N mod 10;
	N:=N div 10;
	IA[I]:=T;
	end;
end;


procedure SquareCubeDigitsPrime(Memo: TMemo);
var Dg1,Dg2: TIntegerDynArray;
var SQ,CU: integer;
var Sum1,Sum2: integer;
var I,J: integer;
var S: string;
begin
S:='';
for I:=1 to 100-1 do
	begin
	SQ:=I*I;
	CU:=I*I*I;
	GetDigits(SQ,Dg1);
	GetDigits(CU,Dg2);
	Sum1:=0;
	for J:=0 to High(Dg1) do Sum1:=Sum1+Dg1[J];
	Sum2:=0;
	for J:=0 to High(Dg2) do Sum2:=Sum2+Dg2[J];
	if IsPrime(Sum1) and IsPrime(Sum2) then
		S:=S+' '+IntToStr(I);
	end;
Memo.Lines.Add(S);
end;
Output:
 16 17 25 28 34 37 47 52 64

Elapsed Time: 1.809 ms.

EasyLang

fastfunc digsum h .
   while h > 0
      sum += h mod 10
      h = h div 10
   .
   return sum
.
fastfunc isprim num .
   if num < 2
      return 0
   .
   i = 2
   while i <= sqrt num
      if num mod i = 0
         return 0
      .
      i += 1
   .
   return 1
.
for i = 1 to 99
   if isprim digsum (i * i) = 1 and isprim digsum (i * i * i) = 1
      write i & " "
   .
.
Output:
16 17 25 28 34 37 47 52 64 

F#

This task uses Extensible Prime Generator (F#)

// Sum of square and cube digits of an integer are primes. Nigel Galloway: December 22nd., 2021
let rec fN g=function 0->g |n->fN(g+n%10)(n/10)
[1..99]|>List.filter(fun g->isPrime(fN 0 (g*g)) && isPrime(fN 0 (g*g*g)))|>List.iter(printf "%d "); printfn ""
Output:
16 17 25 28 34 37 47 52 64

Factor

Works with: Factor version 0.99 2021-06-02
USING: kernel math math.functions math.primes math.text.utils prettyprint sequences ;

100 <iota> [ [ sq ] [ 3 ^ ] bi [ 1 digit-groups sum prime? ] both? ] filter .
Output:
V{ 16 17 25 28 34 37 47 52 64 }

FOCAL

01.10 F I=1,100;D 2
01.20 Q

02.10 F P=2,3;S N=I^P;D 3;D 4;I (C)2.3
02.20 T %2,I,!
02.30 R

03.10 S S=0
03.20 S M=FITR(N/10)
03.30 S S=S+(N-M*10)
03.40 S N=M
03.50 I (-N)3.2

04.10 S C=0
04.20 I (1-S)4.3;S C=-1;R
04.30 I (2-S)4.4;S C=0;R
04.40 F D=2,FSQT(S)+1;D 5;I (C)4.5
04.50 R

05.10 S Z=S/D
05.20 I (FITR(Z)-Z)5.3;S C=-1
05.30 R
Output:
= 16
= 17
= 25
= 28
= 34
= 37
= 47
= 52
= 64

Go

Library: Go-rcu
package main

import (
    "fmt"
    "rcu"
)

func main() {
    for i := 1; i < 100; i++ {
        if !rcu.IsPrime(rcu.DigitSum(i*i, 10)) {
            continue
        }
        if rcu.IsPrime(rcu.DigitSum(i*i*i, 10)) {
            fmt.Printf("%d ", i)
        }
    }
    fmt.Println()
}
Output:
16 17 25 28 34 37 47 52 64 

Haskell

import Data.Bifunctor (first)
import Data.Numbers.Primes (isPrime)

---- SQUARE AND CUBE BOTH HAVE PRIME DECIMAL DIGIT SUMS --

p :: Int -> Bool
p =
  ((&&) . primeDigitSum . (^ 2))
    <*> (primeDigitSum . (^ 3))

--------------------------- TEST -------------------------
main :: IO ()
main = print $ filter p [2 .. 99]

------------------------- GENERIC ------------------------
primeDigitSum :: Int -> Bool
primeDigitSum = isPrime . digitSum 10

digitSum :: Int -> Int -> Int
digitSum base = go
  where
    go 0 = 0
    go n = uncurry (+) . first go $ quotRem n base
Output:
[16,17,25,28,34,37,47,52,64]

J

((1*./@p:[:+/@|:10#.^:_1^&2 3)"0#]) i.100
Output:
16 17 25 28 34 37 47 52 64

Java

import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.IntStream;

public final class SumOfSquareAndCubeDigitsOfAnIntegerArePrimes {

	public static void main(String[] args) {
		Predicate<Integer> isPrime = n ->
			n > 1 && IntStream.rangeClosed(2, (int) Math.sqrt(n)).allMatch( i -> n % i != 0 );
		
		Function<Integer, Integer> digitSum = number -> {
			int sum = 0;
			while ( number > 0 ) {
				sum += number % 10;
				number /= 10;
			}
			return sum;
		};
		
		System.out.println(IntStream.range(1, 100)
			.filter( n -> isPrime.test(digitSum.apply(n * n)) && isPrime.test(digitSum.apply(n * n * n)) )
			.boxed().toList());
	}		
	
}
Output:
[16, 17, 25, 28, 34, 37, 47, 52, 64]

jq

Works with: jq

Also works with gojq and fq

Preliminaries

def is_prime:
  . as $n
  | if ($n < 2)         then false
    elif ($n % 2 == 0)  then $n == 2
    elif ($n % 3 == 0)  then $n == 3
    elif ($n % 5 == 0)  then $n == 5
    elif ($n % 7 == 0)  then $n == 7
    elif ($n % 11 == 0) then $n == 11
    elif ($n % 13 == 0) then $n == 13
    elif ($n % 17 == 0) then $n == 17
    elif ($n % 19 == 0) then $n == 19
    else 23
         | until( (. * .) > $n or ($n % . == 0); .+2)
	 | . * . > $n
    end;

# emit an array of the decimal digits of the integer input, least significant digit first.
def digits:
  recurse( if . >= 10 then ((. - (.%10)) / 10) else empty end) | . % 10;

def digitSum:
  def add(s): reduce s as $_ (0; .+$_);
  add(digits);

The Task

range(1;100)
| (.*.) as $sq
|  select( ($sq | digitSum | is_prime) and ($sq * . | digitSum | is_prime ) )
Output:
16
17
25
28
34
37
47
52
64

Julia

using Primes

is_sqcubsumprime(n) = isprime(sum(digits(n*n))) && isprime(sum(digits(n*n*n)))
println(filter(is_sqcubsumprime, 1:100)) # [16, 17, 25, 28, 34, 37, 47, 52, 64]

MAD

            NORMAL MODE IS INTEGER
            
            BOOLEAN PRIME
            DIMENSION PRIME(100)
            PRIME(0)=0B
            PRIME(1)=0B
            THROUGH SET, FOR P=2, 1, P.G.100
SET         PRIME(P)=1B
            THROUGH SIEVE, FOR P=2, 1, P*P.G.100
            THROUGH SIEVE, FOR C=P*P, P, C.G.100
SIEVE       PRIME(C)=0B
            
            THROUGH CHECK, FOR I=1, 1, I.GE.100
            WHENEVER .NOT.PRIME(DIGSUM.(I*I)), TRANSFER TO CHECK
            WHENEVER .NOT.PRIME(DIGSUM.(I*I*I)), TRANSFER TO CHECK
            PRINT FORMAT FMT, I
CHECK       CONTINUE
            
            INTERNAL FUNCTION(N)
            ENTRY TO DIGSUM.
            SUM=0
            NN=N
LOOP        WHENEVER NN.G.0
                NXT=NN/10
                SUM=SUM+NN-NXT*10
                NN=NXT
                TRANSFER TO LOOP
            END OF CONDITIONAL
            FUNCTION RETURN SUM
            END OF FUNCTION
            
            VECTOR VALUES FMT = $I2*$
            END OF PROGRAM
Output:
16
17
25
28
34
37
47
52
64

Mathematica |Wolfram Language

Translation of: Maple
isSqCubSumPrime[n_Integer] := Module[{sq = n^2, cub = n^3},
  PrimeQ[Total[IntegerDigits[sq]]] && PrimeQ[Total[IntegerDigits[cub]]]
];

Select[Range[100], isSqCubSumPrime] // Print
Output:
{16, 17, 25, 28, 34, 37, 47, 52, 64}


Miranda

main :: [sys_message]
main = [Stdout (show [n | n<-[1..99]; and (map (prime.digitsum.(n^)) [2,3])])]

prime :: num->bool
prime n = n>=2 & and [n mod d ~= 0 | d <- [2..entier (sqrt n)]]

digitsum :: num->num
digitsum = sum . map (mod 10) . takewhile (> 0) . iterate (div 10)
Output:
[16,17,25,28,34,37,47,52,64]

Modula-2

Translation of: XPL0
Works with: ADW Modula-2 version any (Compile with the linker option Console Application).
MODULE SumOfEtc;
(* Sum of square and cube digits of an integer are primes *)

FROM STextIO IMPORT
  WriteLn, WriteString;
FROM SWholeIO IMPORT
  WriteInt;

VAR
  N: CARDINAL;

PROCEDURE IsPrime(Num: CARDINAL): BOOLEAN;
VAR
  I: CARDINAL;
BEGIN
  IF Num < 2 THEN
    RETURN FALSE
  END;
  IF Num = 2 THEN
    RETURN TRUE
  END;
  IF Num MOD 2 = 0 THEN
    RETURN FALSE
  END;
  I := 3;
  WHILE (I * I <= Num) DO
    IF Num MOD I = 0 THEN
      RETURN FALSE
    END;
    I := I + 2;
  END;
  RETURN TRUE;
END IsPrime;

PROCEDURE SumDigits(Num: CARDINAL): CARDINAL;
VAR
  Sum: CARDINAL;
BEGIN
  Sum := 0;
  WHILE Num <> 0 DO
    Sum := Sum + Num MOD 10;
    Num := Num DIV 10;
  END;
  RETURN Sum
END SumDigits;

BEGIN
  FOR N := 0 TO 99 DO
    IF IsPrime(SumDigits(N * N)) AND IsPrime(SumDigits(N * N * N)) THEN
      WriteInt(N, 1);
      WriteString(' ')
    END;
  END;
  WriteLn;
END SumOfEtc.
Output:
16 17 25 28 34 37 47 52 64

Nim

const Primes = {2, 3, 5, 7, 11, 13, 17, 19}

func digitSum(n: Positive): int =
  ## Return the sum of digits of "n".
  var n = n.Natural
  while n != 0:
    result += n mod 10
    n = n div 10

for n in 5..99:
  let  = n * n
  if digitSum() in Primes and digitSum(n * ) in Primes:
    stdout.write n, ' '
echo()
Output:
16 17 25 28 34 37 47 52 64 

OCaml

let is_prime n =
  let rec test x =
    let q = n / x in x > q || x * q <> n && n mod (x + 2) <> 0 && test (x + 6)
  in if n < 5 then n lor 1 = 3 else n land 1 <> 0 && n mod 3 <> 0 && test 5

let rec digit_sum n =
  if n < 10 then n else n mod 10 + digit_sum (n / 10)

let is_square_and_cube_digit_sum_prime n =
  is_prime (digit_sum (n * n)) && is_prime (digit_sum (n * n * n))

let () =
  Seq.ints 1 |> Seq.take_while ((>) 100)
  |> Seq.filter is_square_and_cube_digit_sum_prime
  |> Seq.iter (Printf.printf " %u") |> print_newline
Output:
 16 17 25 28 34 37 47 52 64

Pascal

Free Pascal

Translation of: XPL0
program SumOfEtc;

  { Sum of square and cube digits of an integer are primes }

var
  N: integer;

  function IsPrime(Num: integer): boolean;
  var
    I: integer;
    FoundFac: boolean;
  begin
    if Num < 2 then
      Result := False
    else if Num = 2 then
      Result := True
    else if Num mod 2 = 0 then
      Result := False
    else
    begin
      I := 3;
      FoundFac := False;
      while (I * I <= Num) and not FoundFac do
      begin
        if Num mod I = 0 then
          FoundFac := True;
        I := I + 2;
      end;
      Result := not FoundFac;
    end;
  end;

  function SumDigits(Num: longint): integer;
  var
    Sum: integer;
  begin
    Sum := 0;
    while Num <> 0 do
    begin
      Sum := Sum + Num mod 10;
      Num := Num div 10;
    end;
    Result := Sum;
  end;

begin
  for N := 0 to 99 do
    if IsPrime(SumDigits(N * N)) and IsPrime(SumDigits(N * N * N)) then
      Write(N, ' ');
  WriteLn;
end.
Output:
16 17 25 28 34 37 47 52 64

Perl

Library: ntheory
#!/usr/bin/perl

use strict; # https://rosettacode.org/wiki/Sum_of_square_and_cube_digits_of_an_integer_are_primes
use warnings;
use ntheory qw( is_prime vecsum );

my @results = grep
  is_prime( vecsum( split //, $_ ** 2 ) ) &&
  is_prime( vecsum( split //, $_ ** 3 ) ), 1 .. 100;
print "@results\n";
Output:
16 17 25 28 34 37 47 52 64

Phix

with javascript_semantics
function ipsd(integer n) return is_prime(sum(sq_sub(sprintf("%d",n),'0'))) end function
function scdp(integer n) return ipsd(n*n) and ipsd(n*n*n) end function
pp(filter(tagset(99),scdp))
Output:
{16,17,25,28,34,37,47,52,64}


PHP

Translation of: XPL0
<?php
// Editing Sum of square and cube digits of an integer are primes

function is_prime(int $num): bool {
  if ($num < 2) {
    return false;
  }
  if ($num == 2) {
    return true;
  }
  if ($num % 2 == 0) {
    return false;
  }
  for ($i = 3; $i * $i <= $num; $i += 2) {
    if ($num % $i == 0) {
      return false;
    }
  }
  return true;
}

function sum_digits(int $num): int {
  $sum = 0;
  while ($num != 0) {
    $sum += $num % 10;
    $num = intdiv($num, 10);
  }
  return $sum;
}

for ($n = 0; $n <= 99; $n++) {
  if (is_prime(sum_digits($n * $n)) && is_prime(sum_digits($n * $n * $n))) {
    echo $n . ' ';
  }
}
echo PHP_EOL;
?>
Output:
16 17 25 28 34 37 47 52 64

PL/0

const maxnumber = 99;
var   n, sum, prime, i, i2, i3;
procedure sumdigitsofn;
    var v, vover10;
    begin
        sum := 0;
        v   := n;
        while v > 0 do begin
            vover10 := v / 10;
            sum := sum + ( v - ( vover10 * 10 ) );
            v := vover10
        end
    end;
procedure isnprime;
    var p;
    begin
        prime := 1;
        if n < 2 then prime := 0;
        if n > 2 then begin
            prime := 0;
            if odd( n ) then prime := 1;
            p := 3;
            while p * p <= n * prime do begin
               if n - ( ( n / p ) * p ) = 0 then prime := 0;
               p := p + 2;
            end
        end
    end;
begin
    i := 0;
    while i <= maxnumber do begin
        i  := i + 1;
        i2 := i * i;
        n  := i2;
        call sumdigitsofn;
        n  := sum;
        call isnprime;
        if prime = 1 then begin
            n := i2 * i;
            call sumdigitsofn;
            n := sum;
            call isnprime;
            if prime = 1 then ! i
        end
    end
end.
Output:
         16
         17
         25
         28
         34
         37
         47
         52
         64

Python

Procedural

#!/usr/bin/python

def isPrime(n):
    for i in range(2, int(n**0.5) + 1):
        if n % i == 0:
            return False        
    return True

def digSum(n, b):
    s = 0
    while n:
        s += (n % b)
        n = n // b
    return s

if __name__ == '__main__':
    for n in range(11, 99):
        if isPrime(digSum(n**3, 10)) and isPrime(digSum(n**2, 10)):
            print(n, end = "  ")
Output:
16  17  25  28  34  37  47  52  64

Functional

'''Square and cube both have prime decimal digit sums'''

# p :: Int -> Bool
def p(n):
    '''True if the square and the cube of N both have
       decimal digit sums which are prime.
    '''
    return primeDigitSum(n ** 2) and primeDigitSum(n ** 3)


# ------------------------- TEST -------------------------
# main :: IO ()
def main():
    '''Matches in the range [1..99]'''
    print([
        x for x in range(2, 100)
        if p(x)
    ])


# ----------------------- GENERIC ------------------------

# primeDigitSum :: Int -> Bool
def primeDigitSum(n):
    '''True if the sum of the decimal digits of n is prime.
    '''
    return isPrime(digitSum(10)(n))


# digitSum :: Int -> Int
def digitSum(base):
    '''The sum of the digits of n in a given base.
    '''
    def go(n):
        q, r = divmod(n, base)
        return go(q) + r if n else 0
    return go


# isPrime :: Int -> Bool
def isPrime(n):
    '''True if n is prime.'''
    if n in (2, 3):
        return True
    if 2 > n or 0 == n % 2:
        return False
    if 9 > n:
        return True
    if 0 == n % 3:
        return False

    def q(x):
        return 0 == n % x or 0 == n % (2 + x)

    return not any(map(q, range(5, 1 + int(n ** 0.5), 6)))


# MAIN ---
if __name__ == '__main__':
    main()
Output:
[16, 17, 25, 28, 34, 37, 47, 52, 64]

Quackery

isprime is defined at Primality by trial division#Quackery.

  [ 0 swap
    [ dup while
      10 /mod
      rot + swap
      again ]
   drop ]        is digitsum ( n --> n )

  98 times
   [ i^ 1+ 2 **
     digitsum isprime if
       [  i^ 1+ 3 **
          digitsum isprime if
            [ i^ 1+ echo sp ] ] ]
Output:
16 17 25 28 34 37 47 52 64

Raku

say ^100 .grep: { .².comb.sum.is-prime && .³.comb.sum.is-prime }
Output:
(16 17 25 28 34 37 47 52 64)

Refal

$ENTRY Go {
    = <Prout <Filter SumOfSquareAndCubeDigitsPrime <Iota 1 99>>>;
}

Iota {
    s.End s.End = s.End;
    s.Start s.End = s.Start <Iota <Add 1 s.Start> s.End>;
};

Filter {
    s.F = ;
    s.F t.X e.Y, <Mu s.F t.X>: {
        True = t.X <Filter s.F e.Y>;
        False = <Filter s.F e.Y>;
    };
};

Prime {
    0 = False; 
    1 = False;
    s.N = <Prime s.N 2>;
    s.N s.D, <Compare s.N <Mul s.D s.D>>: '-' = True;
    s.N s.D, <Mod s.N s.D>: 0 = False;
    s.N s.D = <Prime s.N <Add 1 s.D>>;
};

DigitSum {
    0 = 0;
    s.N, <Divmod s.N 10>: (s.R) s.D = <Add s.D <DigitSum s.R>>;
};

SumOfSquareAndCubeDigitsPrime {
    s.N, <Mul s.N s.N>: s.Sq, 
         <Mul s.Sq s.N>: s.Cb,
         <Prime <DigitSum s.Sq>>: True,
         <Prime <DigitSum s.Cb>>: True = True;
    s.N = False;
};
Output:
16 17 25 28 34 37 47 52 64

Ring

load "stdlib.ring"
see "working..." +nl

limit = 100

for n = 1 to limit
    sums = 0
    sumc = 0
    sps = string(pow(n,2))
    spc = string(pow(n,3))
    for m = 1 to len(sps)
        sums = sums + sps[m]
    next
    for p = 1 to len(spc)
        sumc = sumc + spc[p]
    next
    if isprime(sums) and isprime(sumc)
       see "" + n + " "
    ok
next
  
see nl + "done..." + nl
Output:
working...
16 17 25 28 34 37 47 52 64 
done...

RPL

Works with: RPL version HP-49C
« 0
  WHILE OVER REPEAT
     SWAP 10 IDIV2 ROT +
  END NIP
» '∑DIG' STO

« { }
  2 100 FOR j 
     IF j SQ ∑DIG ISPRIME? THEN
        IF j 3 ^ ∑DIG ISPRIME? THEN
           j +
     END END
  NEXT
» 'TASK' STO
Output:
1: { 16 17 25 28 34 37 47 52 64 }

Ruby

require 'prime'

p (1..100).select{|n|(n*n).digits.sum.prime? && (n**3).digits.sum.prime?}
Output:
[16, 17, 25, 28, 34, 37, 47, 52, 64]

Rust

fn is_prime( number : u32 ) -> bool {
   if number < 2 {
      false 
   }
   else {
      let limit : u32 = (number as f32).sqrt( ).floor( ) as u32 ;
      let mut nums : Vec<u32> = Vec::new( ) ;
      for i in 2..=limit {
         nums.push( i ) ;
      }
      nums.iter( ).filter( | n | number % *n == 0 ).count( ) == 0
   }
}

fn to_digits( mut number : u32 ) -> Vec<u32> {
   let mut digits : Vec<u32> = Vec::new( ) ;
   while number != 0 {
      let remainder : u32 = number % 10 ;
      digits.push( remainder ) ;
      number /= 10 ;
   }
   digits
}

fn digit_sum( number : u32 ) -> u32 {
   let digits : Vec<u32> = to_digits( number ) ;
   digits.iter( ).sum( )
}

fn main() {
   let mut solution : Vec<u32> = Vec::new( ) ;
   for i in 2..=100 {
      let square = i * i ;
      let cube = square * i ;
      if is_prime( digit_sum( square ) ) && is_prime( digit_sum(cube ) ) {
         solution.push( i ) ;
      }
   }
   println!("{:?}" , solution);
}
Output:
[16, 17, 25, 28, 34, 37, 47, 52, 64]

SETL

program sum_of_digits_of_square_and_cube_are_prime;
    print({n in {1..99} | prime(digitsum(n**2)) and prime(digitsum(n**3))});

    op prime(n);
        return n>=2 and not exists d in {2..floor sqrt n} | n mod d=0;
    end op;

    op digitsum(n);
        return +/[[n mod 10, n div:= 10](1) : until n=0];
    end op;
end program;
Output:
{16 17 25 28 34 37 47 52 64}

Sidef

1..99 -> grep { .square.digits_sum.is_prime && .cube.digits_sum.is_prime }.say
Output:
[16, 17, 25, 28, 34, 37, 47, 52, 64]

Wren

Library: Wren-math
import "./math" for Int

for (i in 1..99) {
    if (Int.isPrime(Int.digitSum(i*i)) && Int.isPrime(Int.digitSum(i*i*i))) System.write("%(i) ")
}
System.print()
Output:
16 17 25 28 34 37 47 52 64 

XPL0

func IsPrime(N);        \Return 'true' if N is prime
int  N, I;
[if N <= 2 then return N = 2;
if (N&1) = 0 then \even >2\ return false;
for I:= 3 to sqrt(N) do
    [if rem(N/I) = 0 then return false;
    I:= I+1;
    ];
return true;
];

func SumDigits(N);      \Return the sum of digits in N
int  N, Sum;
[Sum:= 0;
while N do
    [N:= N/10;
    Sum:= Sum + rem(0);
    ];
return Sum;
];

int N;
[for N:= 0 to 100-1 do
    if IsPrime(SumDigits(N*N)) & IsPrime(SumDigits(N*N*N)) then
        [IntOut(0, N);  ChOut(0, ^ )];
]
Output:
16 17 25 28 34 37 47 52 64 
Cookies help us deliver our services. By using our services, you agree to our use of cookies.