Check type of an integer

7

You will receive an integer less than 2000000000 and bigger than -2000000000 and you have to test what type(s) of number this is out of:

Factorial
Square
Cube
Prime
Composite
Triangular
Positive
Negative

Here is a definition of all the different types of numbers:

Factorial - A number That is equal to the product of all positive integers less than the a certain positive integer - 5×4×3×2×1 = 120
Square - A number that is the product of two identical integers - 5×5 = 25
Cube - A number that is the product of three identical integers - −5×−5×−5 = -125
Prime - A number that has only two divisors (1 and 0 are not) - 3
Composite - A number that has more than two divisors (also not 1 or 0) - 4
Triangular - A number that is equal the sum of all positive integers less than the a certain positive integer - 5+4+3+2+1 = 15
Positive - A number larger than 0 (not 0) - 7
Negative - A number less than 0 (not 0) - −7

Test Cases

-8 = ["Cube","Negative"]                                   
-2 = ["Negative"]                                          
-1 = ["Cube","Negative"]                                   
 0 = ["Cube", "Square", "Triangular"]                                                    
 1 = ["Cube","Factorial","Positive","Square","Triangular"] 
 2 = ["Factorial","Positive","Prime"]                      
 3 = ["Positive","Prime","Triangular"]                     
 4 = ["Composite","Positive","Square"]                     
 5 = ["Positive","Prime"]                                  
 6 = ["Composite","Factorial","Positive","Triangular"]     
 7 = ["Positive","Prime"]                                  
 8 = ["Composite","Cube","Positive"]                       
 9 = ["Composite","Positive","Square"]                     
10 = ["Composite","Positive","Triangular"]                 
11 = ["Positive","Prime"]                                  
12 = ["Composite","Positive"]                              

Note: The Order of the Result Does Not Matter and it can be expressed with words (Does Not Have To Be A List)

Remember, this is a code golf so the smallest answer in bytes is what I'm looking for

SimpleBinary

Posted 2019-02-26T10:39:09.753

Reputation: 187

6Welcome to PPCG. Nice first challenge. You may want harmonise the casing and/or explicitly state that any casing is acceptable. Does the result have to be a list of strings or is any indication using those words OK? Could we substitute "codes" or bit or synonyms, etc.? – Adám – 2019-02-26T11:38:20.267

2Some more test cases would be nice too. – Adám – 2019-02-26T11:53:50.663

8Is -1 a triangular number? Is -4 a composite number? Please define your types to make the challenge self contained and add some examples. – flawr – 2019-02-26T12:34:34.773

1I really like this challenge idea, it would be nice if you could specify this a bit better. – Rɪᴋᴇʀ – 2019-02-26T15:24:38.050

I've taken the freedom to fix your definitions. Feel free to correct me if I'm wrong. – Adám – 2019-02-26T21:41:53.447

1You should still clarify whether casing is important (as yours is inconsistent) and whether answering by other means than with English words is acceptable. – Adám – 2019-02-26T21:43:19.257

3Do we actually have to be able to handle ±2×10⁹ or is it enough that the algorithm in principle works. Some solutions may want to calculate impractically large factorials or have practical issues with finding primality of large numbers. You may want to allow limiting to what's representable. – Adám – 2019-02-26T22:05:26.563

1The test cases leave out the fact that they are posivite – ASCII-only – 2019-02-27T01:51:25.090

@ASCII-only Fixed. – Adám – 2019-02-27T05:55:45.333

4Is 0 not a square and cube? – Neil A. – 2019-02-27T06:07:33.647

10 is also a triangular number, right? – Embodiment of Ignorance – 2019-02-28T06:22:58.657

It says that the result can be expressed with words, but not that it has to. Should this be interpreted as allowing alternate formats for results, including integer instead of string, etc? – gastropner – 2019-03-01T03:38:19.070

Zero is a square, a cube, and a triangular number. As you haven't as of yet replied to the relevant questions of the commenters above regarding whether a 0 input is a special case (test cases on their own aren't enough to specify the challenge), or edited this challenge to clarify them, I've voted to close it as unclear. – Erik the Outgolfer – 2019-03-02T14:16:03.820

@EriktheOutgolfer 0 x 0 = 0, therefore it is square, 0 is a triangular number, 0 is a cube. 0 is not positive or negative – SimpleBinary – 2019-03-02T23:46:12.567

A number that has only two divisors (1 and 0 are not) - 3. But 3 has only 1 divisor (which is 3). – tsh – 2019-03-04T03:39:43.543

Answers

6

APL (Dyalog Extended), 130 119 bytesSBCS

Anonymous tacit prefix function.

((∊∘⎕A⊂⊢)'FactorialSquareTriangularCubePositiveNegativePrimeComposite')/⍨{⍵∊¨(⊂∘!,×⍨⍮+\)⍳|⍵},(|∊⍳∘|*3⍨),<,>,1∘⍭,0∘⍭∧1∘<

Try it online!

()/⍨ filters the list of strings on the left by the bit mask on the right:

()'Facite' apply the following tacit function to the long string:

  ∊∘⎕A element-wise membership of the uppercase alphabet

   partitions (i.e. True begins a new partition)

   the unmodified argument

The last 46 bytes return a bit vector indicating [Factorial, Square, Triangular, Cube, Positive, Negative, Prime, Composite]:

{⍵∊¨(⊂∘!,×⍨⍮+\)⍳|⍵},(|∊⍳∘|*3⍨),<,>,1∘⍭,0∘⍭∧1∘<

Try it online!

{} the first three bits (factorial, square, triangular) come from this anonymous lambda:

⍵∊¨()… is the argument a member of each of the following three lists?

  ⊂∘! the enclosed factorials

  , followed by

  ×⍨ the squares (lit. the multiplication selfies)

   juxtaposed with

  +\ the running sum

 of the integers one through

|⍵ the absolute value of the argument

() the next bit (cube) comes from the following tacit function:

| is the absolute value of the argument

 a member of

⍳∘| the integers 1 through the absolute value of the argument

* raised to the power of

3⍨ three

< the next bit is simply whether it is positive (zero is less than)

> the next bit is simply whether it is negative (zero is more than)

1∘⍭ the next bit is whether it is prime

0∘⍭ the final bit is whether it is non-prime

1∘< one is less than it

Adám

Posted 2019-02-26T10:39:09.753

Reputation: 37 779

4

JavaScript (ES7),  244 238  236 bytes

Returns an array of strings.

n=>'negative/positive/triangular/cube/square/factorial/prime/composite'.split`/`.filter((s,i)=>(k=!i)?n<0:i-1?i<5?(g=n=>(x=k++**(2+i%2))<n?g(n):x==n)(i-2?i&n<0?-n:n:8*n+1):(g=i-5?k=>n>1?n%--k?g(k):k<2^i>6:0:n=>n>1?g(n/++k):n==1)(n):n>0)

Try it online! or See a formatted version

How?

We filter an array of number properties, keeping track of our current position in the index \$i\$:

 i | Property   | OEIS    | Test
---+------------+---------+---------------------------------------------------------
 0 | negative   | A001478 | n < 0
 1 | positive   | A000027 | n > 0
 2 | triangular | A000217 | look for k >= 0 such that k**2 = 8n+1
 3 | cube       | A000578 | look for k >= 0 such that k**3 = |n|
 4 | square     | A000290 | look for k >= 0 such that k**2 = n
 5 | factorial  | A000142 | divide n by 1, 2, 3, etc. until it's either 1 or < 1
 6 | prime      | A000040 | n > 1 and its largest proper divisor is equal to 1
 7 | composite  | A002808 | n > 1 and its largest proper divisor is greater than 1

Case \$i=0\$ (negative)

We test whether \$n < 0\$.

Case \$i=1\$ (positive)

We test whether \$n > 0\$.

Case \$2\le i \le 4\$ (triangular, cube, square)

We use the following function, starting with \$k=0\$:

g = n =>                   // n = input
  (x = k++ ** (2 + i % 2)) // x = either k**3 if i = 3, or k**2 otherwise; increment k
  < n ?                    // if the above result is less than n:
    g(n)                   //   do a recursive call
  :                        // else:
    x == n                 //   test whether x is equal to n

If \$i=2\$ (triangular test), \$g\$ is called with \$8n+1\$ (i.e. we test whether \$8n+1\$ is a perfect square).

If \$i=3\$ (cube test), \$g\$ is called with \$|n|\$ (i.e. we test whether \$|n|\$ is a perfect cube).

If \$i=4\$ (square test), \$g\$ is called with \$n\$ (i.e. we test whether \$n\$ is a perfect square).

Case \$i=5\$ (factorial)

We use the following function, starting with \$k=0\$:

g = n =>                   // n = input
  n > 1 ?                  // if n is greater than 1:
    g(n / ++k)             //   increment k and do a recursive call with n / k
  :                        // else:
    n == 1                 //   test whether n is equal to 1

Case \$i>5\$ (prime, composite)

We use the following function:

g = k =>                   // k = current divisor, initialized to n
  n > 1 ?                  // if n is greater than 1:
    n % --k ?              //   decrement k; if k is not a divisor of n:
      g(k)                 //     do a recursive call
    :                      //   else:
      k < 2 ^              //     test whether k = 1 (n is prime)
      i > 6                //     invert the result if i = 7
  :                        // else:
    0                      //   always return 0 (n is neither prime nor composite)

Arnauld

Posted 2019-02-26T10:39:09.753

Reputation: 111 334

1"its smallest proper divisor", maybe you mean "largest". – tsh – 2019-03-04T03:44:09.153

3

Japt, 101 96 88 bytes

-5 bytes thanks to Oliver
-8 bytes thanks to Shaggy

`t„gÔ³dÖ%oÐÒdpoÐÓv‚šg…iv‚cu¼çyÜ)Ã$quÂÂpÎX`qd g[U*8Ä ¬v1 Uk ÅÊU¬U<0Uõ³øU UõÊøU U¬v1 Uj]ð

Try it online!

ASCII-only

Posted 2019-02-26T10:39:09.753

Reputation: 4 687

Damn, beat me to doing it :) I need to be faster and online more if I'm ever going to answer anything :P – Quintec – 2019-02-27T02:03:09.863

You could always try using a different approach :P – ASCII-only – 2019-02-27T02:05:25.883

96 bytes – Oliver – 2019-02-27T03:32:10.437

You've been posting some nice Japt answers recently. I have sort of relied on the Japt interpreter the few times I've posted a solution. That's pretty good if you are able to do it w/ TIO. – dana – 2019-02-27T04:59:59.473

3@dana I do use the interpreter every time, just because the quick reference is handy :P it's just that I move it to TIO so it's more consistent with other posts – ASCII-only – 2019-02-27T05:02:23.800

@dana Oh, also Shaggy's compressors come in really when you have strings – ASCII-only – 2019-02-27T10:23:48.010

There's a lot of space + U here, but join + eval might be too costly – ASCII-only – 2019-02-27T11:50:27.597

90 bytes – Shaggy – 2019-02-27T12:51:51.990

I'm working on a new tip on string compression at the moment ;) – Shaggy – 2019-02-27T12:52:14.697

88 bytes – Shaggy – 2019-02-27T12:55:16.413

3

Stax, 79 71 bytes

ë∙☺H▓»░g▬äεê▄ú▓▒º₧Σ↓i∟I∩├▼┬√&A4¼╔uë[Ü▼╒π←=Å♥\aâ╬°Æ■v⌂♂δ┴▄·╠.ë¶<→`┬╪½¥6X

Run and debug it

Unpacked, ungolfed, and commented, it looks like this.

|c      peek input and terminate if falsey
12{|Fm  first 12 factorials
#       (1) is the input found in the array?
x       push original input from x register and 
G       (2) execute program at trailing curly brace which tests for square-ness
x       push original input from x register
|n      get exponents of prime factorization
|g      gcd of array
3%!     (3) is not a multiple of 3
x1|M    push max(1, x) where x is the original input
c       copy value on the stack
|p      (4) is prime?
s       swap top two stack entries
|fD     (5) drop first element from prime factorization
x8*^    push 8x+1 where x is the original input
G       (6) execute program at trailing curly brace which tests for square-ness
x0>     (7) is original input greater than zero?
c!      (8) logically negate the value at (7)
`?|yL843smg!O5&;RVPC3&g9W!ISjvJN'n`
        compressed literal for "negative positive triangular composite prime cube square factorial"
        - these are the names in reverse order of the test results pushed at (1)-(8)
:.j     title case and split on spaces
f       filter list of names and implicitly output using the rest of the program as a predicate
  d     drop the name revealing the corresponding test result on top of the stack
        terminate program
}       `G` target from above; when done, resume execution 
  c|qJ= copy, floor square-root, square, then test equality; this is a test for squareness

Run this one

recursive

Posted 2019-02-26T10:39:09.753

Reputation: 8 616

How does this work? – lirtosiast – 2019-03-03T06:38:57.717

@lirtosiast: added an explanation – recursive – 2019-03-04T02:41:36.270

2

05AB1E, 76 75 bytes

_i¯ë.±D(IŲIÄ©3zmDïQIpIÑg3@Id*®LηPIå®ÅTIå)”îË¢…ï©×Ä›ˆÉíšâialÓª”¨¨"ular"«#sÏ

Try it online or verify all test cases.

Explanation:

_i               # If the (implicit) input is 0:
  ¯              #  Push an empty list
 ë               # Else:
  .±             #  Push the signum of the (implicit) input (-1 if <0; 0 if 0; 1 if >0)
                 #   i.e. -8 → -1
  D(             #  Duplicate and take it's negative
                 #   i.e. -1 → 1
  IŲ            #  Push the input, and check if it's a square
                 #  (negative values will result in the negative numbers themselves)
                 #   i.e. -8 → -8
  IÄ             #  Push the absolute value of the input
                 #   i.e. -8 → 8
    ©            #  Store it in the register (without popping) to reuse later
     3z          #  Push 1/3
       m         #  Take the absolute input to the power of 1/3
                 #  (NOTE: a^(1/3) is the same as ³√a)
                 #   i.e. 8 → 2.0
        DïQ      #  Check if this is an integer without decimal digits
                 #   i.e. 2.0 → 1 (truthy)
  Ip             #  Push the input, and check if it's a prime
                 #   i.e. -8 → 0 (falsey)
  IÑ             #  Push the input, and get a list of its divisors
                 #   i.e. -8 → [1,2,4,8]
    g            #  Take the length of that list
                 #   i.e. [1,2,4,8] → 4
     3@          #  And check if it's larger than or equal to 3
                 #  (the list includes 1, hence the check for >=3 instead of >=2)
                 #   i.e. 4 >= 3 → 1 (truthy)
       Id        #  Push the input again, and check if it's non-negative
                 #   i.e. -8 → 0 (falsey)
         *       #  Check if both are truthy
                 #   i.e. 1 and 0 → 0 (falsey)
  ®L             #  Create a list in the range [1, absolute value of the input]
                 #   i.e. 8 → [1,2,3,4,5,6,7,8]
    η            #  Get a list of prefixes of this list
                 #   → [[1],[1,2],[1,2,3],[1,2,3,4],[1,2,3,4,5],[1,2,3,4,5,6],[1,2,3,4,5,6,7],[1,2,3,4,5,6,7,8]]
     P           #  Get the product for each prefix-list
                 #   → [1,2,6,24,120,720,5040,40320]
      Iå         #  Check if the input is in this list
                 #   i.e. [1,2,6,24,120,720,5040,40320] and -8 → 0 (falsey)
  ®ÅT            #  Create a list of all triangular numbers below or equal to
                 #  the absolute value of the input
                 #   i.e. 8 → [0,1,3,6]
     Iå          #  Check if the input is in this list
                 #   i.e. [0,1,3,6] and -8 → 0 (falsey)
  )              #  Wrap all values on the stack into a single list
                 #   → [-1,1,-8,1,0,0,0,0]
  ”îË¢…ï©×Ä›ˆÉíšâialÓª”
                 #  Push dictionary string "Positive Negative Square Cube Prime Composite Factorial Triangle"
   ¨¨            #  Remove the last two characters (the "le" of "Triangle")
     "ular"«     #  Append "ular"
            #    #  Split this string by spaces
             s   #  Swap to take the earlier created list again
              Ï  #  And only leave the strings at the truthy indices
                 #  (NOTE: Only 1 is truthy in 05AB1E)
                 #   i.e. [-1,1,-8,1,0,0,0,0] → ["Negative","Cube"]
                 # (and output the result implicitly)

See this 05AB1E tip of mine (section How to use the dictionary?) to understand why ”îË¢…ï©×Ä›ˆÉíšâialÓª” is "Positive Negative Square Cube Prime Composite Factorial Triangle".

Kevin Cruijssen

Posted 2019-02-26T10:39:09.753

Reputation: 67 575

1

Python 3, 405 259 bytes

Thanks to @ASCII-only

def z(n):
	x=y=1
	while x<n:x*=y;y+=1
	return"Factorial "*(x==n)+"Square "*(n>=0and n**.5%1==0)+"Cube "*(abs(n)**(1/3)%1==0)+"Negative "*(n<0)+"Positive "*(n>0)+"Triangular "*(n>0and(8*n+1)**.5%1==0)+["Composite ","Prime "][all(n%x for x in range(2,n))]*(n>1)

Try it online!

Old Code

Generates the squares, cubes, and factorials into lists to check against, has a function to check for primality (and consequently compositeness), uses a simple equality to check for positivity/negativity, and checks if 8n+1 is a perfect square to determine if n is a triangular number. Hardcoded the limits for the square, cube, and factorial lists. Returns the answer in a set, which I assume is acceptable (adding elements to a list requires more bytes).

p=lambda n:all(n%x!=0 for x in range(2,n))
def z(n):
	f,a,x,y,s,c=[],set(),1,1,[i*i for i in range(44721)],[i**3 for i in range(-1259,1259)]
	while x<2*10**9:f.append(x);x*=y;y+=1
	if n in f:a.add("Factorial")
	if n in s:a.add("Square")
	if n in c:a.add("Cube")
	if n>0:
		a.add("Positive")
		if 8*n+1 in s:a.add("Triangular")
	if n>1:a.add(("Composite","Prime")[p(n)])
	if n<0:a.add("Negative")
	return a

Try it online!

Neil A.

Posted 2019-02-26T10:39:09.753

Reputation: 2 038

jZNfa6swGMav66fIhIHaDIztztpuDsb@wIExBufciRepjV3ARpfEzXbss/ck0Wqxx8NBLzS/53neNy9JsZVvOZvs90WY4c1yhQFb4Cxz2Hl1FvogzTmoAGWAY7YmTgCZ61orkoKdw9yFNUohhhXcQgGTMIqhepF6IupRY6WddTq9CpAba@ZN@hAFl3M3tkafbzQjoLoJPOR73nyRjsOoiq8rL9xeb8chskY0BUz70gVWzH7Cicw5xZkdd0zU7Nd7iTlpAF4K1bGCSQ3vy@UBsVtf7WRkll9zQSX9MEizmcfG6Cjzt6rF1mWGeWtGhjj2fb4ptJvY0H7ldENsNypUzbgR3vh1xAtZ40MJTmTJGcB7SYRMsCAChCCynIsZBF91j7AzfLtQoUCj3hoalPuaNJOAoNYYcGzppgi7CcDWdrxr4zUtDJjqrRvZRMtO0Gnc1LRyPL6THozu8q95Bv3oRwx01y99NRw560c2w2rVRjX/z96R/w9hvyuEhttCwWCQ5rFlmbvFilJCgJn4JPoPtAdMHfWCUyadRrKrP9S11qdUEOm0K@AsbBL0/ahd9tPdz@fHBwhIVZBEkpV9qOLu/wA – ASCII-only – 2019-02-27T06:21:08.953

381, add https://tio.run/## to start – ASCII-only – 2019-02-27T06:21:25.663

394 bytes. – Jonathan Frech – 2019-02-27T06:23:06.470

358 – ASCII-only – 2019-02-27T06:23:10.257

@ASCII-only 341 bytes.

– Jonathan Frech – 2019-02-27T06:29:47.570

263 – ASCII-only – 2019-02-27T06:49:09.367

2259 – ASCII-only – 2019-02-27T07:31:10.843

0

C# (Visual C# Interactive Compiler), 286 bytes

n=>{int k=0;return(n>0?"Positive":n<0?"Negative":"")+(Math.Sqrt(8*n+1)%1==0?"Triangular":"")+(new int[n].Where((a,b)=>n%++b<1).Count()>2?"Composite":n<3?"":"Prime")+(Math.Pow(n,1/3d)%1>0?"":"Cube")+(Math.Sqrt(n)%1>0?"":"Square")+(g(k)?"Factorial":""));bool g(int i)=>i>1?g(i/++k):1==i;}

Try it online!

Embodiment of Ignorance

Posted 2019-02-26T10:39:09.753

Reputation: 7 014