class Int

Integer (arbitrary-precision)
class Int is Cool does Real { }

Int objects store integral numbers of arbitrary size. Ints are immutable.

There are two main syntax forms for Int literals

123;         # Int in decimal notation
    :16<BEEF>;   # Int in radix notation

For your convenience common radix forms come with a prefix shortcut.

say so :2<11111111> == 0b11111111 == :8<377> == 0o377 == 255 == 0d255 == :16<ff> == 0xff;
    # OUTPUT: «True␤»

All forms allow underscores between any two digits which can serve as visual separators, but don't carry any meaning:

5_00000;       # five Lakhs
    500_000;       # five hundred thousand
    0xBEEF_CAFE;   # a strange place
    :2<1010_1010>; # 0d170

Radix notation also supports round and square brackets which allow you to parse a string for a given base, and putting together digits into a whole number respectively:

:16("9F");         # 159
    :100[99, 2, 3];    # 990203

These notations allow you to use variables, too:

my $two = "2";
    my $ninety-nine = "99";
    :16($ninety-nine); # 153
    :100[99, $two, 3]; # 990203

Methods

method new

multi method new(Any:U $type)
    multi method new(Any:D \value --> Int:D)
    multi method new(int   \value --> Int:D)

The first form will throw an exception; the second and third form will create a new Int from the actual integer value contained in the variable.

method Str

multi method Str(Int:D)
    multi method Str(Int:D, :$superscript)
    multi method Str(Int:D, :$subscript)

Returns a string representation of the number.

say 42.Str;                # OUTPUT: «42␤»

Cool being a parent class of Int, an explicit call to the Int.Str method is seldom needed, unless you want the string to be returned in superscript or subscript.

say 42.Str(:superscript); # OUTPUT: «⁴²␤»
    say 42.Str(:subscript);   # OUTPUT: «₄₂␤»

The :superscript and :subscript named arguments are available as of the 2023.05 Rakudo compiler release.

method Capture

method Capture()

Throws X::Cannot::Capture.

routine chr

multi        chr(Int:D  --> Str:D)
    multi method chr(Int:D: --> Str:D)

Returns a one-character string, by interpreting the integer as a Unicode codepoint number and converting it to the corresponding character.

Example:

65.chr;  # returns "A"
    196.chr; # returns "Ä"

routine expmod

multi        expmod(      $x,     $y,     $mod --> Int:D)
    multi        expmod(Int:D $x, Int $y, Int $mod --> Int:D)
    multi method expmod(Int:D:    Int $y, Int $mod --> Int:D)

Returns the given Int raised to the $y power within modulus $mod, that is gives the result of ($x ** $y) mod $mod. The subroutine form can accept non-Int arguments, which will be coerced to Int.

say expmod(4, 2, 5);    # OUTPUT: «1␤»
    say 7.expmod(2, 5);     # OUTPUT: «4␤»

$y argument can also be negative, in which case, the result is equivalent to ($x ** $y) mod $mod.

say 7.expmod(-2, 5);     # OUTPUT: «4␤»

method polymod

method polymod(Int:D: +@mods)

Returns a sequence of mod results corresponding to the divisors in @mods in the same order as they appear there. For the best effect, the divisors should be given from the smallest "unit" to the largest (e.g. 60 seconds per minute, 60 minutes per hour) and the results are returned in the same way: from smallest to the largest (5 seconds, 4 minutes). The last non-zero value will be the last remainder.

say 120.polymod(10);    # OUTPUT: «(0 12)␤»
    say 120.polymod(10,10); # OUTPUT: «(0 2 1)␤»

In the first case, 120 is divided by 10 giving as a remainder 12, which is the last element. In the second, 120 is divided by 10, giving 12, whose remainder once divided by 10 is 2; the result of the integer division of 12 div 10 is the last remainder. The number of remainders will be always one more item than the number of given divisors. If the divisors are given as a lazy list, runs until the remainder is 0 or the list of divisors is exhausted.

my $seconds = 1 * 60*60*24 # days
                + 3 * 60*60    # hours
                + 4 * 60       # minutes
                + 5;           # seconds
say $seconds.polymod(60, 60);                # OUTPUT: «(5 4 27)␤»
    say $seconds.polymod(60, 60, 24);            # OUTPUT: «(5 4 3 1)␤»
say 120.polymod:      1, 10, 10², 10³, 10⁴;  # OUTPUT: «(0 0 12 0 0 0)␤»
    say 120.polymod: lazy 1, 10, 10², 10³, 10⁴;  # OUTPUT: «(0 0 12)␤»
    say 120.polymod:      1, 10, 10² … ∞;        # OUTPUT: «(0 0 12)␤»
    my @digits-in-base37 = 9123607.polymod(37 xx *); # Base conversion
    say @digits-in-base37.reverse                    # OUTPUT: «[4 32 4 15 36]␤»

All divisors must be Ints when called on an Int.

say 120.polymod(⅓);                            # ERROR

To illustrate how the Int, non-lazy version of polymod works, consider this code that implements it:

my $seconds = 2 * 60*60*24 # days
                + 3 * 60*60    # hours
                + 4 * 60       # minutes
                + 5;           # seconds
my @pieces;
    for 60, 60, 24 -> $divisor {
        @pieces.push: $seconds mod $divisor;
        $seconds div= $divisor
    }
    @pieces.push: $seconds;
say @pieces; # OUTPUT: «[5 4 3 2]␤»

For a more detailed discussion, see this blog post.

We can use lazy lists in polymod, as long as they are finite:

my $some-numbers = lazy gather { take 3*$_ for 1..3 };
say 600.polymod( $some-numbers ); # OUTPUT: «(0 2 6 3)␤»

routine is-prime

multi        is-prime (Int:D $number --> Bool:D)
    multi method is-prime (Int:D: --> Bool:D)

Returns True if this Int is known to be a prime, or is likely to be a prime based on a probabilistic Miller-Rabin test.

Returns False if this Int is known not to be a prime.

say 2.is-prime;         # OUTPUT: «True␤»
    say is-prime(9);        # OUTPUT: «False␤»

routine lsb

multi method lsb(Int:D:)
    multi        lsb(Int:D)

Short for "Least Significant Bit". Returns Nil if the number is 0. Otherwise returns the zero-based index from the right of the least significant (rightmost) 1 in the binary representation of the number.

say 0b01011.lsb;        # OUTPUT: «0␤»
    say 0b01010.lsb;        # OUTPUT: «1␤»
    say 0b10100.lsb;        # OUTPUT: «2␤»
    say 0b01000.lsb;        # OUTPUT: «3␤»
    say 0b10000.lsb;        # OUTPUT: «4␤»

routine msb

multi method msb(Int:D:)
    multi        msb(Int:D)

Short for "Most Significant Bit". Returns Nil if the number is 0. Otherwise returns the zero-based index from the right of the most significant (leftmost) 1 in the binary representation of the number.

say 0b00001.msb;        # OUTPUT: «0␤»
    say 0b00011.msb;        # OUTPUT: «1␤»
    say 0b00101.msb;        # OUTPUT: «2␤»
    say 0b01010.msb;        # OUTPUT: «3␤»
    say 0b10011.msb;        # OUTPUT: «4␤»

routine unival

multi        unival(Int:D  --> Numeric)
    multi method unival(Int:D: --> Numeric)

Returns the number represented by the Unicode codepoint with the given integer number, or NaN if it does not represent a number.

say ord("¾").unival;    # OUTPUT: «0.75␤»
    say 190.unival;         # OUTPUT: «0.75␤»
    say unival(65);         # OUTPUT: «NaN␤»

method Range

Returns a Range object that represents the range of values supported.

method Bridge

method Bridge(Int:D: --> Num:D)

Returns the integer converted to Num.

Operators

infix div

multi infix:<div>(Int:D, Int:D --> Int:D)

Does an integer division, rounded down.

See Also

class int

Native integer

class Allomorph

Dual value number and string

class Any

Thing/object

class AST

Abstract representation of a piece of source code

class atomicint

Integer (native storage at the platform's atomic operation size)

class Block

Code object with its own lexical scope

class CallFrame

Captures the current frame state

class Code

Code object

class Collation

Encapsulates instructions about how strings should be sorted

class Compiler

Information related to the compiler that is being used

class Complex

Complex number

class ComplexStr

Dual value complex number and string

class Cool

Object that can be treated as both a string and number

class CurrentThreadScheduler

Scheduler that synchronously executes code on the current thread

class Date

Calendar date

class DateTime

Calendar date with time

class Distribution::Hash

Distribution::Hash

class Distribution::Locally

Distribution::Locally

class Distribution::Path

Distribution::Path

class Distribution::Resource

Every one of the resources installed with a distribution

class Duration

Length of time

class Encoding::Registry

Management of available encodings

class FatRat

Rational number (arbitrary-precision)

class ForeignCode

Rakudo-specific class that wraps around code in other languages (generally NQP)

class Format

Convert values to a string given a format specification

class Formatter

Produce Callable for given format specification

class HyperSeq

An object for performing batches of work in parallel with ordered output

class HyperWhatever

Placeholder for multiple unspecified values/arguments

class Instant

Specific moment in time

class IntStr

Dual value integer and string

class Junction

Logical superposition of values

class Label

Tagged location in the source code

class Lock::Async

A non-blocking, non-re-entrant, mutual exclusion lock

class Macro

Compile-time routine

class Method

Member function

class Mu

The root of the Raku type hierarchy.

class Nil

Absence of a value or a benign failure

class Num

Floating-point number

role Numeric

Number or object that can act as a number

class NumStr

Dual value floating-point number and string

class ObjAt

Unique identification for an object

class Parameter

Element of a Signature

class Perl

Perl related information

class Proxy

Item container with custom storage and retrieval

class RaceSeq

Performs batches of work in parallel without respecting original order.

class Raku

Raku related information

package RakuAST

Namespace for holding RakuAST related classes

class RakuAST::Doc::Block

Contains the information of a RakuDoc block

class RakuAST::Doc::Declarator

Contains the declarator docs of a RakuAST object

class RakuAST::Doc::Markup

Contains the information about RakuDoc markup

class RakuAST::Doc::Paragraph

Contains the information about a RakuDoc paragraph

class Rat

Rational number (limited-precision)

class RatStr

Dual value rational number and string

class Routine

Code object with its own lexical scope and return handling

class Routine::WrapHandle

Holds all information needed to unwrap a wrapped routine.

class Scalar

A mostly transparent container used for indirections

class Signature

Parameter list pattern

class Str

String of characters

class StrDistance

Contains the result of a string transformation.

class Sub

Subroutine

class Submethod

Member function that is not inherited by subclasses

class Telemetry

Collect performance state for analysis

class Telemetry::Instrument::Thread

Instrument for collecting Thread data

class Telemetry::Instrument::ThreadPool

Instrument for collecting ThreadPoolScheduler data

class Telemetry::Instrument::Usage

Instrument for collecting getrusage data

class Telemetry::Period

Performance data over a period

class Telemetry::Sampler

Telemetry instrument pod

Subset UInt

Unsigned integer (arbitrary-precision)

class ValueObjAt

Unique identification for value types

class Variable

Object representation of a variable for use in traits

class Version

Module version descriptor

class Whatever

Placeholder for the value of an unspecified argument

class WhateverCode

Code object constructed by Whatever-priming

The Camelia image is copyright 2009 by Larry Wall. "Raku" is trademark of the Yet Another Society. All rights reserved.