OPEN-SOURCE SCRIPT

Prime Numbers

416
Prime Numbers highlights prime numbers (no surprise there 😅), tokens and the recent "active" feature in "input".

ekran görüntüsü


🔸 CONCEPTS

🔹 What are Prime Numbers?
A prime number (or a prime) is a natural number greater than 1 that is not a product of two smaller natural numbers.
Wikipedia: Prime number


🔹 Prime Factorization
The fundamental theorem of arithmetic states that every integer larger than 1 can be written as a product of one or more primes. More strongly, this product is unique in the sense that any two prime factorizations of the same number will have the same number of copies of the same primes, although their ordering may differ. So, although there are many different ways of finding a factorization using an integer factorization algorithm, they all must produce the same result. Primes can thus be considered the "basic building blocks" of the natural numbers.
Wikipedia: Fundamental theorem of arithmetic
Math Is Fun: Prime Factorization


We divide a given number by Prime Numbers until only Primes remain.

Example:

Pine Script®
24 / 2 = 12 | 24 / 3 = 8 12 / 3 = 4 | 8 / 2 = 4 4 / 2 = 2 | 4 / 2 = 2 | 24 = 2 x 3 x 2 | 24 = 3 x 2 x 2 or | or 24 = 2² x 3 | 24 = 2² x 3


In other words, every natural/integer number above 1 has a unique representation as a product of prime numbers, no matter how the number is divided. Only the order can change, but the factors (the basic elements) are always the same.


🔸 USAGE

The Prime Numbers publication contains two use cases:
  • Prime Factorization: performed on "close" prices, or a manual chosen number.
  • List Prime Numbers: shows a list of Prime Numbers.

The other two options are discussed in the DETAILS chapter:
  • Prime Factorization Without Arrays
  • Find Prime Numbers


🔹 Prime Factorization

Users can choose to perform Prime Factorization on close prices or a manually given number.

❗️Note that this option only applies to close prices above 1, which are also rounded since Prime Factorization can only be performed on natural (integer) numbers above 1.


In the image below, the left example shows Prime Factorization performed on each close price for the latest 50 bars (which is set with "Run script only on 'Last x Bars'" -> 50).
The right example shows Prime Factorization performed on a manually given number, in this case "1,340,011". This is done only on the last bar.
ekran görüntüsü
When the "Source" option "close price" is chosen, one can toggle "Also current price", where both the historical and the latest current price are factored. If disabled, only historical prices are factored.

Note that, depending on the chosen options, only applicable settings are available, due to a recent feature, namely the parameter "active" in settings.

Setting the "Source" option to "Manual - Limited" will factorize any given number between 1 and 1,340,011, the latter being the highest value in the available arrays with primes.

Setting to "Manual - Not Limited" enables the user to enter a higher number. If all factors of the manual entered number are in the 1 - 1,340,011 range, these factors will be shown; however, if a factor is higher than 1,340,011, the calculation will stop, after which a warning is shown:
ekran görüntüsü

The calculated factors are displayed as a label where identical factors are simplified with an exponent notation in superscript.

For example 2 x 2 x 2 x 5 x 7 x 7 will be noted as 2³ x 5 x 7²

ekran görüntüsü


🔹 List Prime Numbers

ekran görüntüsü
The "List Prime Numbers" option enables users to enter a number, where the first found Prime Number is shown, together with the next x Prime Numbers ("Amount", max. 200)

The highest shown Prime Number is 1,340,011.

One can set the number of shown columns to customize the displayed numbers ("Max. columns", max. 20).


🔸 DETAILS

The Prime Numbers publication consists out of 4 parts:
  • Prime Factorization Without Arrays
  • Prime Factorization
  • List Prime Numbers
  • Find Prime Numbers


The usage of "Prime Factorization" and "List Prime Numbers" is explained above.


🔹 Prime Factorization Without Arrays

This option is only there to highlight a hurdle while performing Prime Factorization.

The basic method of Prime Factorization is to divide the base number by 2, 3, ... until the result is an integer number. Continue until the remaining number and its factors are all primes.

The division should be done by primes, but then you need to know which one is a prime.

In practice, one performs a loop from 2 to the base number.

Example:

Pine Script®
Base_number = input.int(24) arr = array.new<int>() n = Base_number go = true while go for i = 2 to n if n % i == 0 if n / i == 1 go := false arr.push(i) label.new(bar_index, high, str.tostring(arr)) else arr.push(i) n /= i break


Small numbers won't cause issues, but when performing the calculations on, for example, 124,001 and a timeframe of, for example, 1 hour, the script will struggle and finally give a runtime error.

How to solve this?


If we use an array with only primes, we need fewer calculations since if we divide by a non-prime number, we have to divide further until all factors are primes.

I've filled arrays with prime numbers and made libraries of them. (see chapter "Find Prime Numbers" to know how these primes were found).


🔹 Tokens

A hurdle was to fill the libraries with as many prime numbers as possible.
Initially, the maximum token limit of a library was 80K.
Very recently, that limit was lifted to 100K. Kudos to the TradingView developers!

What are tokens?


Tokens are the smallest elements of a program that are meaningful to the compiler. They are also known as the fundamental building blocks of the program.

I have included a code block below the publication code (// - - - Educational (2) - - - ) which, if copied and made to a library, will contain exactly 100K tokens.
Adding more exported functions will throw a "too many tokens" error when saving the library. Subtracting 100K from the shown amount of tokens gives you the amount of used tokens for that particular function.
In that way, one can experiment with the impact of each code addition in terms of tokens.

For example adding the following code in the library:
Pine Script®
export a() => a = array.from(1)
will result in a 100,041 tokens error, in other words (100,041 - 100,000) that functions contains 41 tokens.


Some more examples, some are straightforward, others are not )
Pine Script®
// adding these lines in one of the arrays results in x tokens , 1 // 2 tokens , 111, 111, 111 // 12 tokens , 1111 // 5 tokens , 111111111 // 10 tokens , 1111111111111111111 // 20 tokens , 1234567890123456789 // 20 tokens , 1111111111111111111 + 1 // 20 tokens , 1111111111111111111 + 8 // 20 tokens , 1111111111111111111 + 9 // 20 tokens , 1111111111111111111 * 1 // 20 tokens , 1111111111111111111 * 9 // 21 tokens , 9999999999999999999 // 21 tokens , 1111111111111111111 * 10 // 21 tokens , 11111111111111111110 // 21 tokens

Pine Script®
//adding these functions to the library results in x tokens export f() => 1 // 4 tokens export f() => v = 1 // 4 tokens export f() => var v = 1 // 4 tokens export f() => var v = 1, v // 4 tokens

Pine Script®
//adding these functions to the library results in x tokens export a() => const array<int>a = array.from(1) // 42 tokens export a() => array<int>a = array.from(1) // 42 tokens export a() => a = array.from(1) // 41 tokens export a() => array.from(1) // 32 tokens export a() => a = array.new<int>() // 44 tokens export a() => a = array.new<int>(), a.push(1) // 56 tokens


What if we could lower the amount of tokens, so we can export more Prime Numbers?


Look at this example:
Pine Script®
829111, 829121, 829123, 829151, 829159, 829177, 829187, 829193

Eight numbers contain the same number 8291.
If we make a function that removes recurrent values, we get fewer tokens!
Pine Script®
829111, 829121, 829123, 829151, 829159, 829177, 829187, 829193 //is transformed to: 829111, 21, 23, 51, 59, 77, 87, 93


The code block below the publication code (// - - - Educational (1) - - - ) shows how these values were reduced. With each step of 100, only the first Prime Number is shown fully.
This function could be enhanced even more to reduce recurrent thousands, tens of thousands, etc.

Using this technique enables us to export more Prime Numbers. The number of necessary libraries was reduced to half or less.

The reduced Prime Numbers are restored using the restoreValues() function, found in the library fikira/Primes_4.


🔹 Find Prime Numbers

This function is merely added to show how I filled arrays with Prime Numbers, which were, in turn, added to libraries (after reduction of recurrent values).

To know whether a number is a Prime Number, we divide the given number by values of the Primes array (Primes 2 -> max. 1,340,011). Once the division results in an integer, where the divisor is smaller than the dividend, the calculation stops since the given number is not a Prime.

When we perform these calculations in a loop, we can check whether a series of numbers is a Prime or not. Each time a number is proven not to be a Prime, the loop starts again with a higher number. Once all Primes of the array are used without the result being an integer, we have found a new Prime Number, which is added to the array.

Doing such calculations on one bar will result in a runtime error.

To solve this, the findPrimeNumbers() function remembers the index of the array. Once a limit has been reached on 1 bar (for example, the number of iterations), calculations will stop on that bar and restart on the next bar.

This spreads the workload over several bars, making it possible to continue these calculations without a runtime error.

The result is placed in log.info(), which can be copied and pasted into a hardcoded array of Prime Number values.

These settings adjust the amount of workload per bar:
  • Max Size: maximum size of Primes array.
  • Max Bars Runtime: maximum amount of bars where the function is called.
  • Max Numbers To Process Per Bar: maximum numbers to check on each bar, whether they are Prime Numbers.
  • Max Iterations Per Bar: maximum loop calculations per bar.

ekran görüntüsü


🔹 The End

❗️The code and description is written without the help of an LLM, I've only used Grammarly to improve my description (without AI :) )

Feragatname

Bilgiler ve yayınlar, TradingView tarafından sağlanan veya onaylanan finansal, yatırım, işlem veya diğer türden tavsiye veya tavsiyeler anlamına gelmez ve teşkil etmez. Kullanım Şartları'nda daha fazlasını okuyun.