Cyclotomic polynomial: Difference between revisions

m (Removed a useless variable.)
(→‎{{header|jq}}: task2(10))
 
(46 intermediate revisions by 11 users not shown)
Line 14:
=={{header|C++}}==
{{trans|Java}}
<langsyntaxhighlight lang="cpp">#include <algorithm>
#include <iostream>
#include <initializer_list>
Line 20:
#include <vector>
 
const int MAX_ALL_FACTORS = 100'000100000;
const int algorithm = 2;
int divisions = 0;
Line 532:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>Task 1: cyclotomic polynomials for n <= 30:
Line 578:
CP[10465] has coefficient with magnitude = 10</pre>
 
=={{header|C sharp|C#}}==
{{trans|Java}}
{{works with|C sharp|8}}
<langsyntaxhighlight lang="csharp">using System;
using System.Collections;
using System.Collections.Generic;
Line 816:
};
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 865:
=={{header|D}}==
{{trans|Kotlin}}
<langsyntaxhighlight lang="d">import std.algorithm;
import std.exception;
import std.format;
Line 1,303:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>Task 1: cyclotomic polynomials for n <= 30:
Line 1,348:
CP[6545] has coefficient with magnitude = 9
CP[10465] has coefficient with magnitude = 10</pre>
 
=={{header|Fermat}}==
This isn't terribly efficient if you have to calculate many cyclotomics- store them in an array rather than using recursion instead if you need to do that- but it showcases Fermat's strength at polynomial expressions.
<syntaxhighlight lang="fermat">
&(J=x); {adjoin x as the variable in the polynomials}
 
Func Cyclotomic(n) =
if n=1 then x-1 fi; {first cyclotomic polynomial is x^n-1}
r:=x^n-1; {caclulate cyclotomic by division}
for d = 1 to n-1 do
if Divides(d,n) then
r:=r\Cyclotomic(d)
fi;
od;
r.; {return the polynomial}
Func Hascoef(n, k) =
p:=Cyclotomic(n);
for d = 0 to Deg(p) do
if |(Coef(p,d))|=k then Return(1) fi
od;
0.;
for d = 1 to 30 do
!!(d,' : ',Cyclotomic(d))
od;
 
for m = 1 to 10 do
i:=1;
while not Hascoef(i, m) do
i:+
od;
!!(m,' : ',i);
od;</syntaxhighlight>
 
=={{header|Go}}==
{{trans|Java}}
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,790 ⟶ 1,824:
}
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,839 ⟶ 1,873:
</pre>
<math>Insert formula here</math>
 
=={{header|Haskell}}==
Uses synthetic polynomial division and simple memoization.
 
<syntaxhighlight lang="haskell">import Data.List
import Data.Numbers.Primes (primeFactors)
 
negateVar p = zipWith (*) p $ reverse $ take (length p) $ cycle [1,-1]
 
lift p 1 = p
lift p n = intercalate (replicate (n-1) 0) (pure <$> p)
 
shortDiv :: [Integer] -> [Integer] -> [Integer]
shortDiv p1 (_:p2) = unfoldr go (length p1 - length p2, p1)
where
go (0, _) = Nothing
go (i, h:t) = Just (h, (i-1, zipWith (+) (map (h *) ker) t))
ker = negate <$> p2 ++ repeat 0
 
primePowerFactors = sortOn fst . map (\x-> (head x, length x)) . group . primeFactors
-- simple memoization
cyclotomics :: [[Integer]]
cyclotomics = cyclotomic <$> [0..]
 
cyclotomic :: Int -> [Integer]
cyclotomic 0 = [0]
cyclotomic 1 = [1, -1]
cyclotomic 2 = [1, 1]
cyclotomic n = case primePowerFactors n of
-- for n = 2^k
[(2,h)] -> 1 : replicate (2 ^ (h-1) - 1) 0 ++ [1]
-- for prime n
[(p,1)] -> replicate n 1
-- for power of prime n
[(p,m)] -> lift (cyclotomics !! p) (p^(m-1))
-- for n = 2*p and prime p
[(2,1),(p,1)] -> take (n `div` 2) $ cycle [1,-1]
-- for n = 2*m and odd m
(2,1):_ -> negateVar $ cyclotomics !! (n `div` 2)
-- general case
(p, m):ps -> let cm = cyclotomics !! (n `div` (p ^ m))
in lift (lift cm p `shortDiv` cm) (p^(m-1))</syntaxhighlight>
 
Simple examples
 
<pre>λ> cyclotomic 7
[1,1,1,1,1,1,1]
 
λ> cyclotomic 9
[1,0,0,1,0,0,1]
 
λ> cyclotomic 16
[1,0,0,0,0,0,0,0,1]</pre>
 
The task solution
 
<syntaxhighlight lang="haskell">showPoly [] = "0"
showPoly p = foldl1 (\r -> (r ++) . term) $
dropWhile null $
foldMap (\(c, n) -> [show c ++ expt n]) $
zip (reverse p) [0..]
where
expt = \case 0 -> ""
1 -> "*x"
n -> "*x^" ++ show n
 
term = \case [] -> ""
'0':'*':t -> ""
'-':'1':'*':t -> " - " ++ t
'1':'*':t -> " + " ++ t
'-':t -> " - " ++ t
t -> " + " ++ t
 
main = do
mapM_ (print . showPoly . cyclotomic) [1..30]
putStrLn $ replicate 40 '-'
mapM_ showLine $ take 4 task2
where
showLine (j, i, l) = putStrLn $ concat [ show j
, " appears in CM(", show i
, ") of length ", show l ]
 
-- in order to make computations faster we leave only each 5-th polynomial
task2 = (1,1,2) : tail (search 1 $ zip [0,5..] $ skipBy 5 cyclotomics)
where
search i ((k, p):ps) = if i `notElem` (abs <$> p)
then search i ps
else (i, k, length p) : search (i+1) ((k, p):ps)
 
skipBy n [] = []
skipBy n lst = let (x:_, b) = splitAt n lst in x:skipBy n b</syntaxhighlight>
 
Result
 
<pre>"-1 + x^1"
"1 + x^1"
"1 + x^1 + x^2"
"1 + x^2"
"1 + x^1 + x^2 + x^3 + x^4"
"1 - x^1 + x^2"
"1 + x^1 + x^2 + x^3 + x^4 + x^5 + x^6"
"1 + x^4"
"1 + x^3 + x^6"
"1 - x^1 + x^2 - x^3 + x^4"
"1 + x^1 + x^2 + x^3 + x^4 + x^5 + x^6 + x^7 + x^8 + x^9 + x^10"
"1 - x^2 + x^4"
"1 + x^1 + x^2 + x^3 + x^4 + x^5 + x^6 + x^7 + x^8 + x^9 + x^10 + x^11 + x^12"
"1 - x^1 + x^2 - x^3 + x^4 - x^5 + x^6"
"1 - x^1 + x^3 - x^4 + x^5 - x^7 + x^8"
"1 + x^8"
"1 + x^1 + x^2 + x^3 + x^4 + x^5 + x^6 + x^7 + x^8 + x^9 + x^10 + x^11 + x^12 + x^13 + x^14 + x^15 + x^16"
"1 - x^3 + x^6"
"1 + x^1 + x^2 + x^3 + x^4 + x^5 + x^6 + x^7 + x^8 + x^9 + x^10 + x^11 + x^12 + x^13 + x^14 + x^15 + x^16 + x^17 + x^18"
"1 - x^2 + x^4 - x^6 + x^8"
"1 - x^1 + x^3 - x^4 + x^6 - x^8 + x^9 - x^11 + x^12"
"1 - x^1 + x^2 - x^3 + x^4 - x^5 + x^6 - x^7 + x^8 - x^9 + x^10"
"1 + x^1 + x^2 + x^3 + x^4 + x^5 + x^6 + x^7 + x^8 + x^9 + x^10 + x^11 + x^12 + x^13 + x^14 + x^15 + x^16 + x^17 + x^18 + x^19 + x^20 + x^21 + x^22"
"1 - x^4 + x^8"
"1 + x^5 + x^10 + x^15 + x^20"
"1 - x^1 + x^2 - x^3 + x^4 - x^5 + x^6 - x^7 + x^8 - x^9 + x^10 - x^11 + x^12"
"1 + x^9 + x^18"
"1 - x^2 + x^4 - x^6 + x^8 - x^10 + x^12"
"1 + x^1 + x^2 + x^3 + x^4 + x^5 + x^6 + x^7 + x^8 + x^9 + x^10 + x^11 + x^12 + x^13 + x^14 + x^15 + x^16 + x^17 + x^18 + x^19 + x^20 + x^21 + x^22 + x^23 + x^24 + x^25 + x^26 + x^27 + x^28"
"1 + x^1 - x^3 - x^4 - x^5 + x^7 + x^8"
----------------------------------------
1 appears in CM(1) having 2 terms
2 appears in CM(105) having 49 terms
3 appears in CM(385) having 241 terms
4 appears in CM(1365) having 577 terms
5 appears in CM(1785) having 769 terms
6 appears in CM(2805) having 1281 terms
7 appears in CM(3135) having 1441 terms
8 appears in CP(6545) having 3841 terms
9 appears in CP(6545) having 3841 terms
10 appears in CP(10465) having 6337 terms</pre>
 
Computations take a while...
 
=={{header|J}}==
 
For values up to 70, we can find cyclotomic polynomials by finding a polynomial with roots of unity relatively prime to the order of the polynomial:
 
<syntaxhighlight lang="j">cyclo=: {{<.-:1+(++) p. 1;^0j2p1* y%~1+I.1=y+.1+i.y}}</syntaxhighlight>
 
This approach suggests that cyclotomic polynomial zero should be <tt>f<sub>0</sub>(x)= 1</tt>
 
Routine to find the nth cyclotomic polynomial:
 
<syntaxhighlight lang="j">{{ if.0>nc<'cache' do.cache=:y end.}} (,1);_1 1
 
cyclotomic=: {{
if.y<#cache do.
if.#c=. y{::cache do.
c return.
end.
end.
c=. unpad cyclotomic000 y
if. y>:#cache do. cache=:(100+y){.cache end.
cache=: (<c) y} cache
c
}}
 
cyclotomic000=: {{ assert.0<y
'q p'=. __ q: y
if. 1=#q do.
,(y%*/q) {."0 q#1
elseif.2={.q do.
,(y%*/q) {."0 (* 1 _1 $~ #) cyclotomic */}.q
elseif. 1 e. 1 < p do.
,(y%*/q) {."0 cyclotomic */q
else.
(_1,(-y){.1) pDiv ;+//.@(*/)each/ cyclotomic each}:*/@>,{1,each q
end.
}}
 
 
NB. discard high order zero coefficients in representation of polynomial
unpad=: {.~ 1+0 i:~0=]
 
NB. polynomial division, optimized for somewhat sparse polynomials
pDiv=: {{
q=. $j=. 2 + x -&# y
'x y'=. x,:y
while. j=. j-1 do.
if. 0={.x do. j=. j-<:i=. 0 i.~ 0=x
q=. q,i#0
x=. i |.!.0 x
else.
q=. q, r=. x %&{. y
x=. 1 |.!.0 x - y*r
end.
end.q
}}</syntaxhighlight>
 
If you take all the divisors of a number. (For example, for 12, the divisors are: 1, 2, 3, 4, 6 and 12) and find the product of their cyclotomic polynomials (for example, for 12, x-1, x+1, x<sup>2</sup>+x+1, x<sup>2</sup>+1, x<sup>2</sup>-x+1, and x<sup>4</sup>-x<sup>2</sup>+1) you get x<sup>n</sup>-1 (for 12, that would of course be x<sup>12</sup>-1).
 
Notes:
 
* the coefficients of cyclotomic polynomials after 1 form a palindrome (that's the <tt>q#1</tt> phrase in the implementation).
* the cyclotomic polynomial for a prime number has as many terms as that number, and the coefficients are all 1 (with no intervening zeros -- the highest power is one less than that prime).
* powers of primes add zero coefficients to the polynomial (that's the <tt>,(y%*/q) {."0</tt> ... phrase in the implementation). This means that we can mostly ignore powers of prime numbers -- they're just going to correspond to zeros we add to the base polynomial.
* an even base cyclotomic polynomial is the same as the corresponding odd base cyclotomic polynomial except with x replaced by negative x. (that's the <tt>(* 1 _1 $~ #)</tt> phrase in the implementation.
* To deal with the general case, we use polynomial division, x<sup>n</sup>-1 divided by the polynomial product the cyclotomic polynomials of the proper divisors of number we're looking for.
* <tt>+//.@(*/)</tt> is polynomial product in J.
 
Task examples:
 
<syntaxhighlight lang="j">taskfmt=: {{
c=. ":each j=.cyclotomic y
raw=. rplc&'_-' ;:inv}.,'+';"0|.(*|j)#c('(',[,],')'"_)each '*x^',&":L:0 <"0 i.#c
txt=. raw rplc'(1*x^0)';'1';'(-1*x^0)';'(-1)';'*x^1)';'*x)'
LF,~'CP[',y,&":']= ',rplc&('(x)';'x';'+ (-1)';'- 1')txt rplc'(1*';'(';'(-1*';'(-'
}}
 
taskorder=: {{
r=.$k=.0
while.y>#r do.k=.k+1
if.(1+#r) e.|cyclotomic k do.
r=. r,k
k=. k-1
end.
end.r
}}
 
;taskfmt each 1+i.30
CP[1]= x - 1
CP[2]= x + 1
CP[3]= (x^2) + x + 1
CP[4]= (x^2) + 1
CP[5]= (x^4) + (x^3) + (x^2) + x + 1
CP[6]= (x^2) + (-x) + 1
CP[7]= (x^6) + (x^5) + (x^4) + (x^3) + (x^2) + x + 1
CP[8]= (x^4) + 1
CP[9]= (x^6) + (x^3) + 1
CP[10]= (x^4) + (-x^3) + (x^2) + (-x) + 1
CP[11]= (x^10) + (x^9) + (x^8) + (x^7) + (x^6) + (x^5) + (x^4) + (x^3) + (x^2) + x + 1
CP[12]= (x^4) + (-x^2) + 1
CP[13]= (x^12) + (x^11) + (x^10) + (x^9) + (x^8) + (x^7) + (x^6) + (x^5) + (x^4) + (x^3) + (x^2) + x + 1
CP[14]= (x^6) + (-x^5) + (x^4) + (-x^3) + (x^2) + (-x) + 1
CP[15]= (x^8) + (-x^7) + (x^5) + (-x^4) + (x^3) + (-x) + 1
CP[16]= (x^8) + 1
CP[17]= (x^16) + (x^15) + (x^14) + (x^13) + (x^12) + (x^11) + (x^10) + (x^9) + (x^8) + (x^7) + (x^6) + (x^5) + (x^4) + (x^3) + (x^2) + x + 1
CP[18]= (x^6) + (-x^3) + 1
CP[19]= (x^18) + (x^17) + (x^16) + (x^15) + (x^14) + (x^13) + (x^12) + (x^11) + (x^10) + (x^9) + (x^8) + (x^7) + (x^6) + (x^5) + (x^4) + (x^3) + (x^2) + x + 1
CP[20]= (x^8) + (-x^6) + (x^4) + (-x^2) + 1
CP[21]= (x^12) + (-x^11) + (x^9) + (-x^8) + (x^6) + (-x^4) + (x^3) + (-x) + 1
CP[22]= (x^10) + (-x^9) + (x^8) + (-x^7) + (x^6) + (-x^5) + (x^4) + (-x^3) + (x^2) + (-x) + 1
CP[23]= (x^22) + (x^21) + (x^20) + (x^19) + (x^18) + (x^17) + (x^16) + (x^15) + (x^14) + (x^13) + (x^12) + (x^11) + (x^10) + (x^9) + (x^8) + (x^7) + (x^6) + (x^5) + (x^4) + (x^3) + (x^2) + x + 1
CP[24]= (x^8) + (-x^4) + 1
CP[25]= (x^20) + (x^15) + (x^10) + (x^5) + 1
CP[26]= (x^12) + (-x^11) + (x^10) + (-x^9) + (x^8) + (-x^7) + (x^6) + (-x^5) + (x^4) + (-x^3) + (x^2) + (-x) + 1
CP[27]= (x^18) + (x^9) + 1
CP[28]= (x^12) + (-x^10) + (x^8) + (-x^6) + (x^4) + (-x^2) + 1
CP[29]= (x^28) + (x^27) + (x^26) + (x^25) + (x^24) + (x^23) + (x^22) + (x^21) + (x^20) + (x^19) + (x^18) + (x^17) + (x^16) + (x^15) + (x^14) + (x^13) + (x^12) + (x^11) + (x^10) + (x^9) + (x^8) + (x^7) + (x^6) + (x^5) + (x^4) + (x^3) + (x^2) + x + 1
CP[30]= (x^8) + (x^7) + (-x^5) + (-x^4) + (-x^3) + x + 1
 
(,.~#\) taskorder 10
1 1
2 105
3 385
4 1365
5 1785
6 2805
7 3135
8 6545
9 6545
10 10465</syntaxhighlight>
 
=== Another approach ===
 
As noted in the [http://jsoftware.com/pipermail/programming/2022-March/060209.html J programming forum], we can improve the big-O character of this algorithm by using the [[Fast Fourier transform#J|fast fourier transform]] for polynomial multiplication and division.
 
<syntaxhighlight lang="j">NB. install'math/fftw'
require'math/fftw'
 
cyclotomic000=: {{ assert.0<y
if. y = 1 do. _1 1 return. end.
'q p'=. __ q: y
if. 1=#q do.
,(y%*/q) {."0 q#1
elseif.2={.q do.
,(y%*/q) {."0 (* 1 _1 $~ #) cyclotomic */}.q
elseif. 1 e. 1 < p do.
,(y%*/q) {."0 cyclotomic */q
else.
lgl=. {:$ ctlist=. cyclotomic "0 }:*/@>,{1,each q NB. ctlist is 2-d table of polynomial divisors
lgd=. # dividend=. _1,(-y){.1 NB. (x^n) - 1, and its size
lg=. >.&.(2&^.) lgl >. lgd NB. required lengths of all polynomials for fft transforms
NB. really, "divisor" is the fft of the divisor!
divisor=. */ fftw"1 lg{."1 ctlist NB. FFT article doesn't deal with lists of multiplicands
unpad roundreal ifftw"1 divisor %~ fftw lg{.dividend NB. similar to article's multiplication
end.
}}
 
roundreal =: [: <. 0.5 + 9&o.</syntaxhighlight>
 
This variation for polynomial division is only valid when there's no remainder to be concerned with (which is the case, here). The article mentioned in the comments is an essay on using [[j:Essays/FFT|fft for polynomial multiplication]]
 
This approach gave slightly over a 16x speedup for <tt>taskorder 10</tt>, from a 2 element cache, with an approximately 50% increased memory footprint. (Remember, of course, that benchmarks and benchmark ratios have dependencies on computer architecture and language implementation, and the host environment.)
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">
import java.util.ArrayList;
import java.util.Collections;
Line 2,368 ⟶ 2,703:
 
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,414 ⟶ 2,749:
CP[6545] has coefficient with magnitude = 9
CP[10465] has coefficient with magnitude = 10
</pre>
 
===Alternative Version===
An alternative example using the algorithm from "Matters Computational" by Jorg Arndt, pages 704 - 705.
It completes the task in less than 2 seconds.
<syntaxhighlight lang="java">
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
 
public class CyclotomicPolynomials {
 
public static void main(String[] args) {
System.out.println("Task 1: Cyclotomic polynomials for n <= 30:");
for ( int cpIndex = 1; cpIndex <= 30; cpIndex++ ) {
System.out.println("CP[" + cpIndex + "] = " + toString(cyclotomicPolynomial(cpIndex)));
}
System.out.println();
System.out.println("Task 2: Smallest cyclotomic polynomial with n or -n as a coefficient:");
System.out.println("CP[1] has a coefficient with magnitude 1");
int cpIndex = 2;
for ( int coefficient = 2; coefficient <= 10; coefficient++ ) {
while ( BigInteger.valueOf(cpIndex).isProbablePrime(PRIME_CERTAINTY)
|| ! hasHeight(cyclotomicPolynomial(cpIndex), coefficient) ) {
cpIndex += 1;
}
System.out.println("CP[" + cpIndex + "] has a coefficient with magnitude " + coefficient);
}
}
// Return the Cyclotomic Polynomial of order 'cpIndex' as an array of coefficients,
// where, for example, the polynomial 3x^2 - 1 is represented by the array [3, 0, -1].
private static int[] cyclotomicPolynomial(int cpIndex) {
int[] polynomial = new int[] { 1, -1 };
if ( cpIndex == 1 ) {
return polynomial;
}
if ( BigInteger.valueOf(cpIndex).isProbablePrime(PRIME_CERTAINTY) ) {
int[] result = new int[cpIndex];
Arrays.fill(result, 1);
return result;
}
List<Integer> primes = distinctPrimeFactors(cpIndex);
int product = 1;
for ( int prime : primes ) {
int[] numerator = substituteExponent(polynomial, prime);
polynomial = exactDivision(numerator, polynomial);
product *= prime;
}
polynomial = substituteExponent(polynomial, cpIndex / product);
return polynomial;
}
// Return the Cyclotomic Polynomial obtained from 'polynomial' by replacing x with x^'exponent'.
private static int[] substituteExponent(int[] polynomial, int exponent) {
int[] result = new int[exponent * ( polynomial.length - 1 ) + 1];
for ( int i = polynomial.length - 1; i >= 0; i-- ) {
result[i * exponent] = polynomial[i];
}
return result;
}
// Return the Cyclotomic Polynomial equal to 'dividend' / 'divisor'. The division is always exact.
private static int[] exactDivision(int[] dividend, int[] divisor) {
int[] result = Arrays.copyOf(dividend, dividend.length);
for ( int i = 0; i < dividend.length - divisor.length + 1; i++ ) {
if ( result[i] != 0 ) {
for ( int j = 1; j < divisor.length; j ++ ) {
result[i + j] += -divisor[j] * result[i];
}
}
}
result = Arrays.copyOf(result, result.length - divisor.length + 1);
return result;
}
 
// Return whether 'polynomial' has a coefficient of equal magnitude to 'coefficient'.
private static boolean hasHeight(int[] polynomial, int coefficient) {
for ( int i = 0; i <= ( polynomial.length + 1 ) / 2; i++ ) {
if ( Math.abs(polynomial[i]) == coefficient ) {
return true;
}
}
return false;
}
// Return a string representation of 'polynomial'.
private static String toString(int[] polynomial) {
StringBuilder text = new StringBuilder();
for ( int i = 0; i < polynomial.length; i++ ) {
if ( polynomial[i] == 0 ) {
continue;
}
text.append(( polynomial[i] < 0 ) ? ( ( i == 0 ) ? "-" : " - " ) : ( ( i == 0 ) ? "" : " + " ));
final int exponent = polynomial.length - 1 - i;
if ( exponent > 0 && Math.abs(polynomial[i]) > 1 ) {
text.append(Math.abs(polynomial[i]));
}
text.append(( exponent > 1 ) ?
( "x^" + String.valueOf(exponent) ) : ( ( exponent == 1 ) ? "x" : Math.abs(polynomial[i]) ));
}
return text.toString();
}
// Return a list of the distinct prime factors of 'number'.
private static List<Integer> distinctPrimeFactors(int number) {
List<Integer> primeFactors = new ArrayList<Integer>();
for ( int divisor = 2; divisor * divisor <= number; divisor++ ) {
if ( number % divisor == 0 ) {
primeFactors.add(divisor);
}
while ( number % divisor == 0 ) {
number = number / divisor;
}
}
if ( number > 1 ) {
primeFactors.add(number);
}
return primeFactors;
}
private static final int PRIME_CERTAINTY = 15;
 
}
</syntaxhighlight>
<pre>
Task 1: Cyclotomic polynomials for n <= 30:
CP[1] = x - 1
CP[2] = x + 1
CP[3] = x^2 + x + 1
CP[4] = x^2 + 1
CP[5] = x^4 + x^3 + x^2 + x + 1
CP[6] = x^2 - x + 1
CP[7] = x^6 + x^5 + x^4 + x^3 + x^2 + x + 1
CP[8] = x^4 + 1
CP[9] = x^6 + x^3 + 1
CP[10] = x^4 - x^3 + x^2 - x + 1
CP[11] = x^10 + x^9 + x^8 + x^7 + x^6 + x^5 + x^4 + x^3 + x^2 + x + 1
CP[12] = x^4 - x^2 + 1
CP[13] = x^12 + x^11 + x^10 + x^9 + x^8 + x^7 + x^6 + x^5 + x^4 + x^3 + x^2 + x + 1
CP[14] = x^6 - x^5 + x^4 - x^3 + x^2 - x + 1
CP[15] = x^8 - x^7 + x^5 - x^4 + x^3 - x + 1
CP[16] = x^8 + 1
CP[17] = x^16 + x^15 + x^14 + x^13 + x^12 + x^11 + x^10 + x^9 + x^8 + x^7 + x^6 + x^5 + x^4 + x^3 + x^2 + x + 1
CP[18] = x^6 - x^3 + 1
CP[19] = x^18 + x^17 + x^16 + x^15 + x^14 + x^13 + x^12 + x^11 + x^10 + x^9 + x^8 + x^7 + x^6 + x^5 + x^4 + x^3 + x^2 + x + 1
CP[20] = x^8 - x^6 + x^4 - x^2 + 1
CP[21] = x^12 - x^11 + x^9 - x^8 + x^6 - x^4 + x^3 - x + 1
CP[22] = x^10 - x^9 + x^8 - x^7 + x^6 - x^5 + x^4 - x^3 + x^2 - x + 1
CP[23] = x^22 + x^21 + x^20 + x^19 + x^18 + x^17 + x^16 + x^15 + x^14 + x^13 + x^12 + x^11 + x^10 + x^9 + x^8 + x^7 + x^6 + x^5 + x^4 + x^3 + x^2 + x + 1
CP[24] = x^8 - x^4 + 1
CP[25] = x^20 + x^15 + x^10 + x^5 + 1
CP[26] = x^12 - x^11 + x^10 - x^9 + x^8 - x^7 + x^6 - x^5 + x^4 - x^3 + x^2 - x + 1
CP[27] = x^18 + x^9 + 1
CP[28] = x^12 - x^10 + x^8 - x^6 + x^4 - x^2 + 1
CP[29] = x^28 + x^27 + x^26 + x^25 + x^24 + x^23 + x^22 + x^21 + x^20 + x^19 + x^18 + x^17 + x^16 + x^15 + x^14 + x^13 + x^12 + x^11 + x^10 + x^9 + x^8 + x^7 + x^6 + x^5 + x^4 + x^3 + x^2 + x + 1
CP[30] = x^8 + x^7 - x^5 - x^4 - x^3 + x + 1
 
Task 2: Smallest cyclotomic polynomial with n or -n as a coefficient:
CP[1] has a coefficient with magnitude 1
CP[105] has a coefficient with magnitude 2
CP[385] has a coefficient with magnitude 3
CP[1365] has a coefficient with magnitude 4
CP[1785] has a coefficient with magnitude 5
CP[2805] has a coefficient with magnitude 6
CP[3135] has a coefficient with magnitude 7
CP[6545] has a coefficient with magnitude 8
CP[6545] has a coefficient with magnitude 9
CP[10465] has a coefficient with magnitude 10
</pre>
 
=={{header|jq}}==
'''Adapted from the [[#Wren|Wren]] implementation of the Arndt algorithm'''
 
'''Works with jq, the C implementation of jq'''
 
'''Works with gojq, the Go implementation of jq'''
 
'''Works with jaq, the Rust implementation of jq'''
 
In this entry, a polynomial of degree n is represented by a JSON
array of length n+1 beginning with the leading coefficient.
 
For the second task, besides exploiting the fact that
CP[1] has height 1, the following program only assumes that the
cyclotomic polynomials are palindromic, but avoids recomputing them.
<syntaxhighlight lang="jq">
### Generic utilities
 
def lpad($len): tostring | ($len - length) as $l | (" " * $l) + .;
 
# Return the maximum item in the stream assuming it is not empty:
def max(s): reduce s as $s (null; if . == null then $s elif $s > . then $s else . end);
 
# Truncated integer division (consistent with % operator).
# `round` is used for the sake of jaq.
def quo($x; $y): ($x - ($x%$y)) / $y | round;
 
### Primes
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 sqrt as $s
| 23
| until( . > $s or ($n % . == 0); . + 2)
| . > $s
end;
 
# Emit an array of the distinct prime factors of 'n' in order using a wheel
# with basis [2, 3, 5], e.g. 44 | distinctPrimeFactors #=> [2,11]
def distinctPrimeFactors:
def augment($x): if .[-1] == $x then . else . + [$x] end;
def out($i):
if (.n % $i) == 0
then .factors += [$i]
| until (.n % $i != 0; .n = ((.n/$i)|floor) )
else .
end;
if . < 2 then []
else [4, 2, 4, 2, 4, 6, 2, 6] as $inc
| { n: .,
factors: [] }
| out(2)
| out(3)
| out(5)
| .k = 7
| .i = 0
| until(.k * .k > .n;
if .n % .k == 0
then .k as $k | .factors |= augment($k)
| .n = ((.n/.k)|floor)
else .k += $inc[.i]
| .i = ((.i + 1) % 8)
end)
| if .n > 1 then .n as $n | .factors |= augment($n) else . end
| .factors
end;
 
### Polynomials
def canonical:
if length == 0 then .
elif .[-1] == 0 then .[:-1]|canonical
else .
end;
 
# For pretty-printing the input array as the polynomial it represents
# e.g. [1,-1] => x-1
def pp:
def digits: tostring | explode[] | [.] | implode | tonumber;
def superscript:
if . <= 1 then ""
else ["\u2070", "\u00b9", "\u00b2", "\u00b3", "\u2074", "\u2075", "\u2076", "\u2077", "\u2078", "\u2079"] as $ss
| reduce digits as $d (""; . + $ss[$d] )
end;
 
if length == 1 then .[0] | tostring
else reverse as $p
| reduce range(length-1; -1; -1) as $i ([];
if $p[$i] != 0
then (if $i > 0 then "x" else "" end) as $x
| ( if $i > 0 and ($p[$i]|length) == 1
then (if $p[$i] == 1 then "" else "-" end)
else ($p[$i]|tostring)
end ) as $c
| . + ["\($c)\($x)\($i|superscript)"]
else . end )
| join("+")
| gsub("\\+-"; "-")
end ;
 
def polynomialDivide($divisor):
. as $in
| ($divisor|canonical) as $divisor
| { curr: canonical}
| .base = ((.curr|length) - ($divisor|length))
| until( .base < 0;
(.curr[-1] / $divisor[-1]) as $res
| .result += [$res]
| .curr |= .[:-1]
| reduce range (0;$divisor|length-1) as $i (.;
.curr[.base + $i] += (- $res * $divisor[$i]) )
| .base += -1 )
| (.result | reverse) as $quot
| (.curr | canonical) as $rem
| [$quot, $rem];
 
# Call `round` for the sake of jaq
def exactDivision($numerator; $denominator):
($numerator | polynomialDivide($denominator))
| .[0]
| map(round);
 
def init($n; $value): [range(0;$n)|$value];
 
### Cyclotomic Polynomials
 
# The Cyclotomic Polynomial obtained from $polynomial
# by replacing x with x^$exponent
def substituteExponent($polynomial; $exponent):
init( ($polynomial|length - 1) * $exponent + 1; 0)
| reduce range(0; $polynomial|length) as $i (.; .[$i*$exponent] = $polynomial[$i]);
 
# Return the Cyclotomic Polynomial of order 'cpIndex' as a JSON array of coefficients,
# where, for example, the polynomial 3x^2 - 1 is represented by [3, 0, -1].
def cycloPoly($cpIndex):
{ polynomial: [1, -1] }
| if $cpIndex == 1 then .polynomial
elif ($cpIndex|is_prime) then [range(0; $cpIndex) | 1 ]
else .product = 1
| reduce ($cpIndex | distinctPrimeFactors[]) as $prime (.;
substituteExponent(.polynomial; $prime) as $numerator
| .polynomial = exactDivision($numerator; .polynomial)
| .product *= $prime )
| substituteExponent(.polynomial; quo($cpIndex; .product) )
end;
 
# The Cyclotomic Polynomial equal to $dividend / $divisor
def exactDivision($dividend; $divisor):
reduce range(0; 1 + ($dividend|length) - ($divisor|length)) as $i ($dividend;
if .[$i] != 0
then reduce range(1; $divisor|length) as $j (.;
.[$i+$j] = .[$i+$j] - $divisor[$j] * .[$i] )
else .
end)
| .[0: 1 + length - ($divisor|length)];
 
### The tasks
def task1($n):
"Task 1: Cyclotomic polynomials for n <= \($n):",
( range(1;$n+1) | "CP[\(lpad(2))]: \(cycloPoly(.)|pp)" );
 
# For range(1;$n+1) as $c, report the first cpIndex which has a coefficient
# equal in magnitude to $c, possibly reporting others as well.
def task2($n):
def height: max(.[]|length); # i.e. abs
# update .summary and .todo
def register($cpIndex):
cycloPoly($cpIndex) as $poly
| if ($poly|height) < .todo[0] then .
else # it is a palindrome so we can halve the checks
reduce ($poly | .[0: quo(length + 1; 2)][]|length|select(.>1)) as $c (.;
if .summary[$c|tostring] then .
else .summary[$c|tostring] = $cpIndex
| .todo -= [$c]
| debug
end)
end;
 
{cpIndex:1, summary: {"1": 1}, todo: [range(2; $n + 1)]}
| until(.todo|length == 0;
if .cpIndex|is_prime then . else register(.cpIndex) end
| .cpIndex += 1)
| .summary
| (keys | sort_by(tonumber)[]) as $key
| "CP[\(.[$key]|lpad(5))] has a coefficient with magnitude \($key)"
;
 
task1(30),
"",
task2(10)
</syntaxhighlight>
{{output}}
<pre>
Task 1: Cyclotomic polynomials for n <= 30:
CP[ 1]: x-1
CP[ 2]: x+1
CP[ 3]: x²+x+1
CP[ 4]: x²+1
CP[ 5]: x⁴+x³+x²+x+1
CP[ 6]: x²-x+1
CP[ 7]: x⁶+x⁵+x⁴+x³+x²+x+1
CP[ 8]: x⁴+1
CP[ 9]: x⁶+x³+1
CP[10]: x⁴-x³+x²-x+1
CP[11]: x¹⁰+x⁹+x⁸+x⁷+x⁶+x⁵+x⁴+x³+x²+x+1
CP[12]: x⁴-x²+1
CP[13]: x¹²+x¹¹+x¹⁰+x⁹+x⁸+x⁷+x⁶+x⁵+x⁴+x³+x²+x+1
CP[14]: x⁶-x⁵+x⁴-x³+x²-x+1
CP[15]: x⁸-x⁷+x⁵-x⁴+x³-x+1
CP[16]: x⁸+1
CP[17]: x¹⁶+x¹⁵+x¹⁴+x¹³+x¹²+x¹¹+x¹⁰+x⁹+x⁸+x⁷+x⁶+x⁵+x⁴+x³+x²+x+1
CP[18]: x⁶-x³+1
CP[19]: x¹⁸+x¹⁷+x¹⁶+x¹⁵+x¹⁴+x¹³+x¹²+x¹¹+x¹⁰+x⁹+x⁸+x⁷+x⁶+x⁵+x⁴+x³+x²+x+1
CP[20]: x⁸-x⁶+x⁴-x²+1
CP[21]: x¹²-x¹¹+x⁹-x⁸+x⁶-x⁴+x³-x+1
CP[22]: x¹⁰-x⁹+x⁸-x⁷+x⁶-x⁵+x⁴-x³+x²-x+1
CP[23]: x²²+x²¹+x²⁰+x¹⁹+x¹⁸+x¹⁷+x¹⁶+x¹⁵+x¹⁴+x¹³+x¹²+x¹¹+x¹⁰+x⁹+x⁸+x⁷+x⁶+x⁵+x⁴+x³+x²+x+1
CP[24]: x⁸-x⁴+1
CP[25]: x²⁰+x¹⁵+x¹⁰+x⁵+1
CP[26]: x¹²-x¹¹+x¹⁰-x⁹+x⁸-x⁷+x⁶-x⁵+x⁴-x³+x²-x+1
CP[27]: x¹⁸+x⁹+1
CP[28]: x¹²-x¹⁰+x⁸-x⁶+x⁴-x²+1
CP[29]: x²⁸+x²⁷+x²⁶+x²⁵+x²⁴+x²³+x²²+x²¹+x²⁰+x¹⁹+x¹⁸+x¹⁷+x¹⁶+x¹⁵+x¹⁴+x¹³+x¹²+x¹¹+x¹⁰+x⁹+x⁸+x⁷+x⁶+x⁵+x⁴+x³+x²+x+1
CP[30]: x⁸+x⁷-x⁵-x⁴-x³+x+1
 
Task 2: Smallest cyclotomic polynomial with n or -n as a coefficient:
CP[ 1] has a coefficient with magnitude 1
CP[ 105] has a coefficient with magnitude 2
CP[ 385] has a coefficient with magnitude 3
CP[ 1365] has a coefficient with magnitude 4
CP[ 1785] has a coefficient with magnitude 5
CP[ 2805] has a coefficient with magnitude 6
CP[ 3135] has a coefficient with magnitude 7
CP[ 6545] has a coefficient with magnitude 8
CP[ 6545] has a coefficient with magnitude 9
CP[10465] has a coefficient with magnitude 10
CP[10465] has a coefficient with magnitude 11
CP[10465] has a coefficient with magnitude 12
CP[10465] has a coefficient with magnitude 13
CP[10465] has a coefficient with magnitude 14
</pre>
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">using Primes, Polynomials
# memoize cache for recursive calls
Line 2,474 ⟶ 3,242:
println("The cyclotomic polynomial Φ(", abs(n), ") has a coefficient that is ", n < 0 ? -i : i)
end
</langsyntaxhighlight>{{out}}
<pre>
First 30 cyclotomic polynomials:
Line 2,521 ⟶ 3,289:
=={{header|Kotlin}}==
{{trans|Java}}
<langsyntaxhighlight lang="scala">import java.util.TreeMap
import kotlin.math.abs
import kotlin.math.pow
Line 2,977 ⟶ 3,745:
} else coefficient.toString() + "x^" + exponent
}
}</langsyntaxhighlight>
{{out}}
<pre>Task 1: cyclotomic polynomials for n <= 30:
Line 3,022 ⟶ 3,790:
CP[6545] has coefficient with magnitude = 9
CP[10465] has coefficient with magnitude = 10</pre>
 
=={{header|Maple}}==
<syntaxhighlight lang="maple">with(NumberTheory):
for n to 30 do lprint(Phi(n,x)) od:
 
x-1
x+1
x^2+x+1
x^2+1
x^4+x^3+x^2+x+1
x^2-x+1
x^6+x^5+x^4+x^3+x^2+x+1
x^4+1
x^6+x^3+1
x^4-x^3+x^2-x+1
x^10+x^9+x^8+x^7+x^6+x^5+x^4+x^3+x^2+x+1
x^4-x^2+1
x^12+x^11+x^10+x^9+x^8+x^7+x^6+x^5+x^4+x^3+x^2+x+1
x^6-x^5+x^4-x^3+x^2-x+1
x^8-x^7+x^5-x^4+x^3-x+1
x^8+1
x^16+x^15+x^14+x^13+x^12+x^11+x^10+x^9+x^8+x^7+x^6+x^5+x^4+x^3+x^2+x+1
x^6-x^3+1
x^18+x^17+x^16+x^15+x^14+x^13+x^12+x^11+x^10+x^9+x^8+x^7+x^6+x^5+x^4+x^3+x^2+x+1
x^8-x^6+x^4-x^2+1
x^12-x^11+x^9-x^8+x^6-x^4+x^3-x+1
x^10-x^9+x^8-x^7+x^6-x^5+x^4-x^3+x^2-x+1
x^22+x^21+x^20+x^19+x^18+x^17+x^16+x^15+x^14+x^13+x^12+x^11+x^10+x^9+x^8+x^7+x^6+x^5+x^4+x^3+x^2+x+1
x^8-x^4+1
x^20+x^15+x^10+x^5+1
x^12-x^11+x^10-x^9+x^8-x^7+x^6-x^5+x^4-x^3+x^2-x+1
x^18+x^9+1
x^12-x^10+x^8-x^6+x^4-x^2+1
x^28+x^27+x^26+x^25+x^24+x^23+x^22+x^21+x^20+x^19+x^18+x^17+x^16+x^15+x^14+x^13+x^12+x^11+x^10+x^9+x^8+x^7+x^6+x^5+x^4+x^3+x^2+x+1
x^8+x^7-x^5-x^4-x^3+x+1
 
PhiSet:=[seq(map(abs,{coeffs(Phi(k,x),x)}),k=1..15000)]:
[seq(ListTools:-SelectFirst(s->member(n,s),PhiSet,output=indices),n=1..20)];
#[1, 105, 385, 1365, 1785, 2805, 3135, 6545, 6545, 10465, 10465,
# 10465, 10465, 10465, 11305, 11305, 11305, 11305, 11305, 11305]</syntaxhighlight>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">Cyclotomic[#, x] & /@ Range[30] // Column
i = 1;
n = 10;
PrintTemporary[Dynamic[{magnitudes, i}]];
magnitudes = ConstantArray[True, n];
While[Or @@ magnitudes,
coeff = Abs[CoefficientList[Cyclotomic[i, x], x]];
coeff = Select[coeff, Between[{1, n}]];
coeff = DeleteDuplicates[coeff];
If[Or @@ magnitudes[[coeff]],
Do[
If[magnitudes[[c]] == True,
Print["CyclotomicPolynomial(", i,
") has coefficient with magnitude ", c]
]
,
{c, coeff}
];
magnitudes[[coeff]] = False;
];
i++;
]</syntaxhighlight>
{{out}}
<pre>-1+x
1+x
1+x+x^2
1+x^2
1+x+x^2+x^3+x^4
1-x+x^2
1+x+x^2+x^3+x^4+x^5+x^6
1+x^4
1+x^3+x^6
1-x+x^2-x^3+x^4
1+x+x^2+x^3+x^4+x^5+x^6+x^7+x^8+x^9+x^10
1-x^2+x^4
1+x+x^2+x^3+x^4+x^5+x^6+x^7+x^8+x^9+x^10+x^11+x^12
1-x+x^2-x^3+x^4-x^5+x^6
1-x+x^3-x^4+x^5-x^7+x^8
1+x^8
1+x+x^2+x^3+x^4+x^5+x^6+x^7+x^8+x^9+x^10+x^11+x^12+x^13+x^14+x^15+x^16
1-x^3+x^6
1+x+x^2+x^3+x^4+x^5+x^6+x^7+x^8+x^9+x^10+x^11+x^12+x^13+x^14+x^15+x^16+x^17+x^18
1-x^2+x^4-x^6+x^8
1-x+x^3-x^4+x^6-x^8+x^9-x^11+x^12
1-x+x^2-x^3+x^4-x^5+x^6-x^7+x^8-x^9+x^10
1+x+x^2+x^3+x^4+x^5+x^6+x^7+x^8+x^9+x^10+x^11+x^12+x^13+x^14+x^15+x^16+x^17+x^18+x^19+x^20+x^21+x^22
1-x^4+x^8
1+x^5+x^10+x^15+x^20
1-x+x^2-x^3+x^4-x^5+x^6-x^7+x^8-x^9+x^10-x^11+x^12
1+x^9+x^18
1-x^2+x^4-x^6+x^8-x^10+x^12
1+x+x^2+x^3+x^4+x^5+x^6+x^7+x^8+x^9+x^10+x^11+x^12+x^13+x^14+x^15+x^16+x^17+x^18+x^19+x^20+x^21+x^22+x^23+x^24+x^25+x^26+x^27+x^28
1+x-x^3-x^4-x^5+x^7+x^8
 
CyclotomicPolynomial(1) has coefficient with magnitude 1
CyclotomicPolynomial(105) has coefficient with magnitude 2
CyclotomicPolynomial(385) has coefficient with magnitude 3
CyclotomicPolynomial(1365) has coefficient with magnitude 4
CyclotomicPolynomial(1785) has coefficient with magnitude 5
CyclotomicPolynomial(2805) has coefficient with magnitude 6
CyclotomicPolynomial(3135) has coefficient with magnitude 7
CyclotomicPolynomial(6545) has coefficient with magnitude 8
CyclotomicPolynomial(6545) has coefficient with magnitude 9
CyclotomicPolynomial(10465) has coefficient with magnitude 10</pre>
 
=={{header|Nim}}==
Line 3,028 ⟶ 3,902:
We use Java algorithm with ideas from C#, D, Go and Kotlin. We have kept only algorithm number 2 as other algorithms are much less efficient. We have also done some Nim specific improvements in order to get better performances.
 
<langsyntaxhighlight Nimlang="nim">import algorithm, math, sequtils, strformat, tables
 
type
Line 3,362 ⟶ 4,236:
echo &"Φ{'(' & $n & ')':7} has coefficient with magnitude = {i}"
dec n
break</langsyntaxhighlight>
 
{{out}}
Line 3,410 ⟶ 4,284:
Φ(6545) has coefficient with magnitude = 9
Φ(10465) has coefficient with magnitude = 10</pre>
 
=={{header|PARI/GP}}==
Cyclotomic polynomials are a built-in function.
<syntaxhighlight lang="parigp">
for(n=1,30,print(n," : ",polcyclo(n)))
 
contains_coeff(n, d) = p=polcyclo(n);for(k=0,poldegree(p),if(abs(polcoef(p,k))==d,return(1)));return(0)
 
for(d=1,10,i=1; while(contains_coeff(i,d)==0,i=i+1);print(d," : ",i))
</syntaxhighlight>
 
{{out}}<pre>
1 : x - 1
2 : x + 1
3 : x^2 + x + 1
4 : x^2 + 1
5 : x^4 + x^3 + x^2 + x + 1
6 : x^2 - x + 1
7 : x^6 + x^5 + x^4 + x^3 + x^2 + x + 1
8 : x^4 + 1
9 : x^6 + x^3 + 1
10 : x^4 - x^3 + x^2 - x + 1
11 : x^10 + x^9 + x^8 + x^7 + x^6 + x^5 + x^4 + x^3 + x^2 + x + 1
12 : x^4 - x^2 + 1
13 : x^12 + x^11 + x^10 + x^9 + x^8 + x^7 + x^6 + x^5 + x^4 + x^3 + x^2 + x + 1
14 : x^6 - x^5 + x^4 - x^3 + x^2 - x + 1
15 : x^8 - x^7 + x^5 - x^4 + x^3 - x + 1
16 : x^8 + 1
17 : x^16 + x^15 + x^14 + x^13 + x^12 + x^11 + x^10 + x^9 + x^8 + x^7 + x^6 + x^5 + x^4 + x^3 + x^2 + x + 1
18 : x^6 - x^3 + 1
19 : x^18 + x^17 + x^16 + x^15 + x^14 + x^13 + x^12 + x^11 + x^10 + x^9 + x^8 + x^7 + x^6 + x^5 + x^4 + x^3 + x^2 + x + 1
20 : x^8 - x^6 + x^4 - x^2 + 1
21 : x^12 - x^11 + x^9 - x^8 + x^6 - x^4 + x^3 - x + 1
22 : x^10 - x^9 + x^8 - x^7 + x^6 - x^5 + x^4 - x^3 + x^2 - x + 1
23 : x^22 + x^21 + x^20 + x^19 + x^18 + x^17 + x^16 + x^15 + x^14 + x^13 + x^12 + x^11 + x^10 + x^9 + x^8 + x^7 + x^6 + x^5 + x^4 + x^3 + x^2 + x + 1
24 : x^8 - x^4 + 1
25 : x^20 + x^15 + x^10 + x^5 + 1
26 : x^12 - x^11 + x^10 - x^9 + x^8 - x^7 + x^6 - x^5 + x^4 - x^3 + x^2 - x + 1
27 : x^18 + x^9 + 1
28 : x^12 - x^10 + x^8 - x^6 + x^4 - x^2 + 1
29 : x^28 + x^27 + x^26 + x^25 + x^24 + x^23 + x^22 + x^21 + x^20 + x^19 + x^18 + x^17 + x^16 + x^15 + x^14 + x^13 + x^12 + x^11 + x^10 + x^9 + x^8 + x^7 + x^6 + x^5 + x^4 + x^3 + x^2 + x + 1
30 : x^8 + x^7 - x^5 - x^4 - x^3 + x + 1
1 : 1
2 : 105
3 : 385
4 : 1365
5 : 1785
6 : 2805
7 : 3135
8 : 6545
9 : 6545
10 : 10465
</pre>
 
=={{header|Perl}}==
Conveniently, the module <code>Math::Polynomial::Cyclotomic</code> exists to do all the work. An <code>exponent too large</code> error prevents reaching the 10th step of the 2nd part of the task.
<langsyntaxhighlight lang="perl">use feature 'say';
use List::Util qw(first);
use Math::Polynomial::Cyclotomic qw(cyclo_poly_iterate);
Line 3,430 ⟶ 4,357:
$n++;
}
}</langsyntaxhighlight>
{{out}}
<pre>First 30 cyclotomic polynomials:
Line 3,478 ⟶ 4,405:
{{trans|Julia}}
Uses several routines from [[Polynomial_long_division#Phix]], tweaked slightly to check remainder is zero and trim the quotient.
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>-- demo\rosetta\Cyclotomic_Polynomial.exw
<span style="color: #000080;font-style:italic;">-- demo\rosetta\Cyclotomic_Polynomial.exw</span>
function degree(sequence p)
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
for i=length(p) to 1 by -1 do
<span style="color: #008080;">function</span> <span style="color: #000000;">degree</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">p</span><span style="color: #0000FF;">)</span>
if p[i]!=0 then return i end if
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">p</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">to</span> <span style="color: #000000;">1</span> <span style="color: #008080;">by</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
end for
<span style="color: #008080;">if</span> <span style="color: #000000;">p</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]!=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span> <span style="color: #008080;">return</span> <span style="color: #000000;">i</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
return -1
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end function
<span style="color: #008080;">return</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">1</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
function poly_div(sequence n, d)
while length(d)<length(n) do d &=0 end while
<span style="color: #008080;">function</span> <span style="color: #000000;">poly_div</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">d</span><span style="color: #0000FF;">)</span>
integer dn = degree(n),
<span style="color: #008080;">while</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">d</span><span style="color: #0000FF;">)<</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span> <span style="color: #000000;">d</span> <span style="color: #0000FF;">&=</span><span style="color: #000000;">0</span> <span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
dd = degree(d)
<span style="color: #004080;">integer</span> <span style="color: #000000;">dn</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">degree</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">),</span>
if dd<0 then throw("divide by zero") end if
<span style="color: #000000;">dd</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">degree</span><span style="color: #0000FF;">(</span><span style="color: #000000;">d</span><span style="color: #0000FF;">)</span>
sequence quot = repeat(0,dn)
<span style="color: #008080;">if</span> <span style="color: #000000;">dd</span><span style="color: #0000FF;"><</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span> <span style="color: #008080;">throw</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"divide by zero"</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
while dn>=dd do
<span style="color: #004080;">sequence</span> <span style="color: #000000;">quot</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">dn</span><span style="color: #0000FF;">)</span>
integer k = dn-dd
<span style="color: #008080;">while</span> <span style="color: #000000;">dn</span><span style="color: #0000FF;">>=</span><span style="color: #000000;">dd</span> <span style="color: #008080;">do</span>
integer qk = n[dn]/d[dd]
<span style="color: #004080;">integer</span> <span style="color: #000000;">k</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">dn</span><span style="color: #0000FF;">-</span><span style="color: #000000;">dd</span>
quot[k+1] = qk
<span style="color: #004080;">integer</span> <span style="color: #000000;">qk</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">[</span><span style="color: #000000;">dn</span><span style="color: #0000FF;">]/</span><span style="color: #000000;">d</span><span style="color: #0000FF;">[</span><span style="color: #000000;">dd</span><span style="color: #0000FF;">]</span>
sequence d2 = d[1..length(d)-k]
<span style="color: #000000;">quot</span><span style="color: #0000FF;">[</span><span style="color: #000000;">k</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">qk</span>
for i=1 to length(d2) do
<span style="color: #004080;">sequence</span> <span style="color: #000000;">d2</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">d</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">..</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">d</span><span style="color: #0000FF;">)-</span><span style="color: #000000;">k</span><span style="color: #0000FF;">]</span>
n[-i] -= d2[-i]*qk
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">d2</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
end for
<span style="color: #004080;">integer</span> <span style="color: #000000;">mi</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">i</span>
dn = degree(n)
<span style="color: #000000;">n</span><span style="color: #0000FF;">[</span><span style="color: #000000;">mi</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">-=</span> <span style="color: #000000;">d2</span><span style="color: #0000FF;">[</span><span style="color: #000000;">mi</span><span style="color: #0000FF;">]*</span><span style="color: #000000;">qk</span>
end while
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
-- return {quot,n} -- (n is now the remainder)
<span style="color: #000000;">dn</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">degree</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
if n!=repeat(0,length(n)) then ?9/0 end if
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
while quot[$]=0 do quot = quot[1..$-1] end while
<span style="color: #000080;font-style:italic;">-- return {quot,n} -- (n is now the remainder)</span>
return quot
<span style="color: #008080;">if</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">!=</span><span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">))</span> <span style="color: #008080;">then</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">9</span><span style="color: #0000FF;">/</span><span style="color: #000000;">0</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end function
<span style="color: #008080;">while</span> <span style="color: #000000;">quot</span><span style="color: #0000FF;">[$]=</span><span style="color: #000000;">0</span> <span style="color: #008080;">do</span> <span style="color: #000000;">quot</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">quot</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">..$-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span> <span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">quot</span>
function poly(sequence si)
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
-- display helper
string r = ""
<span style="color: #008080;">function</span> <span style="color: #000000;">poly</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">si</span><span style="color: #0000FF;">)</span>
for t=length(si) to 1 by -1 do
<span style="color: #000080;font-style:italic;">-- display helper</span>
integer sit = si[t]
<span style="color: #004080;">string</span> <span style="color: #000000;">r</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">""</span>
if sit!=0 then
<span style="color: #008080;">for</span> <span style="color: #000000;">t</span><span style="color: #0000FF;">=</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">si</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">to</span> <span style="color: #000000;">1</span> <span style="color: #008080;">by</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
if sit=1 and t>1 then
<span style="color: #004080;">integer</span> <span style="color: #000000;">sit</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">si</span><span style="color: #0000FF;">[</span><span style="color: #000000;">t</span><span style="color: #0000FF;">]</span>
r &= iff(r=""? "":" + ")
<span style="color: #008080;">if</span> <span style="color: #000000;">sit</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
elsif sit=-1 and t>1 then
<span style="color: #008080;">if</span> <span style="color: #000000;">sit</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">and</span> <span style="color: #000000;">t</span><span style="color: #0000FF;">></span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span>
r &= iff(r=""?"-":" - ")
<span style="color: #000000;">r</span> <span style="color: #0000FF;">&=</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">r</span><span style="color: #0000FF;">=</span><span style="color: #008000;">""</span><span style="color: #0000FF;">?</span> <span style="color: #008000;">""</span><span style="color: #0000FF;">:</span><span style="color: #008000;">" + "</span><span style="color: #0000FF;">)</span>
else
<span style="color: #008080;">elsif</span> <span style="color: #000000;">sit</span><span style="color: #0000FF;">=-</span><span style="color: #000000;">1</span> <span style="color: #008080;">and</span> <span style="color: #000000;">t</span><span style="color: #0000FF;">></span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span>
if r!="" then
<span style="color: #000000;">r</span> <span style="color: #0000FF;">&=</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">r</span><span style="color: #0000FF;">=</span><span style="color: #008000;">""</span><span style="color: #0000FF;">?</span><span style="color: #008000;">"-"</span><span style="color: #0000FF;">:</span><span style="color: #008000;">" - "</span><span style="color: #0000FF;">)</span>
r &= iff(sit<0?" - ":" + ")
<span sit style="color: abs(sit)#008080;">else</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">r</span><span style="color: #0000FF;">!=</span><span style="color: #008000;">""</span> <span style="color: #008080;">then</span>
end if
<span style="color: #000000;">r</span> <span style="color: #0000FF;">&=</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sit</span><span style="color: #0000FF;"><</span><span style="color: #000000;">0</span><span style="color: #0000FF;">?</span><span style="color: #008000;">" - "</span><span style="color: #0000FF;">:</span><span style="color: #008000;">" + "</span><span style="color: #0000FF;">)</span>
r &= sprintf("%d",sit)
<span style="color: #000000;">sit</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">abs</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sit</span><span style="color: #0000FF;">)</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
r &= iff(t>1?"x"&iff(t>2?sprintf("^%d",t-1):""):"")
<span style="color: #000000;">r</span> <span style="color: #0000FF;">&=</span> <span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"%d"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">sit</span><span style="color: #0000FF;">)</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end for
<span style="color: #000000;">r</span> <span style="color: #0000FF;">&=</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t</span><span style="color: #0000FF;">></span><span style="color: #000000;">1</span><span style="color: #0000FF;">?</span><span style="color: #008000;">"x"</span><span style="color: #0000FF;">&</span><span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t</span><span style="color: #0000FF;">></span><span style="color: #000000;">2</span><span style="color: #0000FF;">?</span><span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"^%d"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">t</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">):</span><span style="color: #008000;">""</span><span style="color: #0000FF;">):</span><span style="color: #008000;">""</span><span style="color: #0000FF;">)</span>
if r="" then r="0" end if
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
return r
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end function
<span style="color: #008080;">if</span> <span style="color: #000000;">r</span><span style="color: #0000FF;">=</span><span style="color: #008000;">""</span> <span style="color: #008080;">then</span> <span style="color: #000000;">r</span><span style="color: #0000FF;">=</span><span style="color: #008000;">"0"</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
--</Polynomial_long_division.exw>
<span style="color: #008080;">return</span> <span style="color: #000000;">r</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
--# memoize cache for recursive calls
<span style="color: #000080;font-style:italic;">--&lt;/Polynomial_long_division.exw&gt;
constant cyclotomics = new_dict({{1,{-1,1}},{2,{1,1}}})
--# memoize cache for recursive calls</span>
function cyclotomic(integer n)
<span style="color: #008080;">constant</span> <span style="color: #000000;">cyclotomics</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">new_dict</span><span style="color: #0000FF;">({{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,{-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">}},{</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">}}})</span>
--
-- Calculate nth cyclotomic polynomial.
<span style="color: #008080;">function</span> <span style="color: #000000;">cyclotomic</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
-- See wikipedia article at bottom of section /wiki/Cyclotomic_polynomial#Fundamental_tools
<span style="color: #000080;font-style:italic;">--
-- The algorithm is reliable but slow for large n > 1000.
-- Calculate the nth cyclotomic polynomial.
--
-- See wikipedia article at bottom of section /wiki/Cyclotomic_polynomial#Fundamental_tools
sequence c
-- The algorithm is reliable but slow for large n &gt; 1000.
if getd_index(n,cyclotomics)!=NULL then
--</span>
c = getd(n,cyclotomics)
<span style="color: #004080;">sequence</span> <span style="color: #000000;">c</span>
else
<span style="color: #008080;">if</span> <span style="color: #7060A8;">getd_index</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">cyclotomics</span><span style="color: #0000FF;">)!=</span><span style="color: #004600;">NULL</span> <span style="color: #008080;">then</span>
if is_prime(n) then
<span style="color: #000000;">c</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">getd</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">cyclotomics</span><span style="color: #0000FF;">)</span>
c = repeat(1,n)
<span style="color: #008080;">else</span>
else -- recursive formula seen in wikipedia article
<span style="color: #008080;">if</span> <span style="color: #7060A8;">is_prime</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
c = -1&repeat(0,n-1)&1
<span style="color: #000000;">c</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
sequence f = factors(n,-1)
<span style="color: #008080;">else</span> <span style="color: #000080;font-style:italic;">-- recursive formula seen in wikipedia article</span>
for i=1 to length(f) do
<span style="color: #000000;">c</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">&</span><span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)&</span><span style="color: #000000;">1</span>
c = poly_div(c,cyclotomic(f[i]))
<span style="color: #004080;">sequence</span> <span style="color: #000000;">f</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">factors</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
end for
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">f</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
end if
<span style="color: #000000;">c</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">poly_div</span><span style="color: #0000FF;">(</span><span style="color: #000000;">c</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">deep_copy</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cyclotomic</span><span style="color: #0000FF;">(</span><span style="color: #000000;">f</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">])))</span>
setd(n,c,cyclotomics)
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
return c
<span style="color: #7060A8;">setd</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">c</span><span style="color: #0000FF;">,</span><span style="color: #000000;">cyclotomics</span><span style="color: #0000FF;">)</span>
end function
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">c</span>
for i=1 to 30 do
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
sequence z = cyclotomic(i)
string s = poly(z)
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">30</span> <span style="color: #008080;">do</span>
printf(1,"cp(%2d) = %s\n",{i,s})
<span style="color: #004080;">sequence</span> <span style="color: #000000;">z</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">cyclotomic</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">)</span>
if i>1 and z!=reverse(z) then ?9/0 end if -- sanity check
<span style="color: #004080;">string</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">poly</span><span style="color: #0000FF;">(</span><span style="color: #000000;">z</span><span style="color: #0000FF;">)</span>
end for
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"cp(%2d) = %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,</span><span style="color: #000000;">s</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">></span><span style="color: #000000;">1</span> <span style="color: #008080;">and</span> <span style="color: #000000;">z</span><span style="color: #0000FF;">!=</span><span style="color: #7060A8;">reverse</span><span style="color: #0000FF;">(</span><span style="color: #000000;">z</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">9</span><span style="color: #0000FF;">/</span><span style="color: #000000;">0</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span> <span style="color: #000080;font-style:italic;">-- sanity check</span>
integer found = 0, n = 1, cheat = 0
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
sequence fn = repeat(false,10),
nxt = {105,385,1365,1785,2805,3135,6545,6545,10465,10465}
<span style="color: #004080;">integer</span> <span style="color: #000000;">found</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">cheat</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
atom t1 = time()+1
<span style="color: #004080;">sequence</span> <span style="color: #000000;">fn</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #004600;">false</span><span style="color: #0000FF;">,</span><span style="color: #000000;">10</span><span style="color: #0000FF;">),</span>
puts(1,"\n")
<span style="color: #000000;">nxt</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">105</span><span style="color: #0000FF;">,</span><span style="color: #000000;">385</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1365</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1785</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2805</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3135</span><span style="color: #0000FF;">,</span><span style="color: #000000;">6545</span><span style="color: #0000FF;">,</span><span style="color: #000000;">6545</span><span style="color: #0000FF;">,</span><span style="color: #000000;">10465</span><span style="color: #0000FF;">,</span><span style="color: #000000;">10465</span><span style="color: #0000FF;">}</span>
while found<10 do
<span style="color: #004080;">atom</span> <span style="color: #000000;">t1</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">time</span><span style="color: #0000FF;">()+</span><span style="color: #000000;">1</span>
sequence z = cyclotomic(n)
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\n"</span><span style="color: #0000FF;">)</span>
for i=1 to length(z) do
<span style="color: #008080;">while</span> <span style="color: #000000;">found</span><span style="color: #0000FF;"><</span><span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">platform</span><span style="color: #0000FF;">()=</span><span style="color: #004600;">JS</span><span style="color: #0000FF;">?</span><span style="color: #000000;">5</span><span style="color: #0000FF;">:</span><span style="color: #000000;">10</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
atom azi = abs(z[i])
<span style="color: #004080;">sequence</span> <span style="color: #000000;">z</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">cyclotomic</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
if azi>=1 and azi<=10 and fn[azi]=0 then
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">z</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
printf(1,"cp(%d) has a coefficient with magnitude %d\n",{n,azi})
<span style="color: #004080;">atom</span> <span style="color: #000000;">azi</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">abs</span><span style="color: #0000FF;">(</span><span style="color: #000000;">z</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">])</span>
cheat = azi -- (comment this out to prevent cheating!)
<span style="color: #008080;">if</span> <span style="color: #000000;">azi</span><span style="color: #0000FF;">>=</span><span style="color: #000000;">1</span> <span style="color: #008080;">and</span> <span style="color: #000000;">azi</span><span style="color: #0000FF;"><=</span><span style="color: #000000;">10</span> <span style="color: #008080;">and</span> <span style="color: #000000;">fn</span><span style="color: #0000FF;">[</span><span style="color: #000000;">azi</span><span style="color: #0000FF;">]=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
found += 1
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"cp(%d) has a coefficient with magnitude %d\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">azi</span><span style="color: #0000FF;">})</span>
fn[azi] = true
<span style="color: #000000;">cheat</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">azi</span> <span style="color: #000080;font-style:italic;">-- (comment this out to prevent cheating!)</span>
t1 = time()+1
<span style="color: #000000;">found</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
end if
<span style="color: #000000;">fn</span><span style="color: #0000FF;">[</span><span style="color: #000000;">azi</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #004600;">true</span>
end for
<span style="color: #000000;">t1</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">time</span><span style="color: #0000FF;">()+</span><span style="color: #000000;">1</span>
if cheat then {n,cheat} = {nxt[cheat],0} else n += iff(n=1?4:10) end if
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
if time()>t1 then
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
printf(1,"working (%d) ...\r",n)
<span style="color: #008080;">if</span> <span style="color: #000000;">cheat</span> <span style="color: #008080;">then</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">cheat</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">nxt</span><span style="color: #0000FF;">[</span><span style="color: #000000;">cheat</span><span style="color: #0000FF;">],</span><span style="color: #000000;">0</span><span style="color: #0000FF;">}</span> <span style="color: #008080;">else</span> <span style="color: #000000;">n</span> <span style="color: #0000FF;">+=</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span><span style="color: #0000FF;">?</span><span style="color: #000000;">4</span><span style="color: #0000FF;">:</span><span style="color: #000000;">10</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
t1 = time()+1
<span style="color: #008080;">if</span> <span style="color: #7060A8;">time</span><span style="color: #0000FF;">()></span><span style="color: #000000;">t1</span> <span style="color: #008080;">and</span> <span style="color: #7060A8;">platform</span><span style="color: #0000FF;">()!=</span><span style="color: #004600;">JS</span> <span style="color: #008080;">then</span>
end if
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"working (%d) ...\r"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
end while</lang>
<span style="color: #000000;">t1</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">time</span><span style="color: #0000FF;">()+</span><span style="color: #000000;">1</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<!--</syntaxhighlight>-->
{{out}}
If you disable the cheating, and if in a particularly self harming mood replace it with n+=1, you will get exactly the same output, eventually.<br>
Line 3,638 ⟶ 4,569:
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">from itertools import count, chain
from collections import deque
 
Line 3,759 ⟶ 4,690:
while want in c or -want in c:
print(f'C[{want}]: {n}')
want += 1</langsyntaxhighlight>
{{out}}
Only showing first 10 polynomials to avoid clutter.
Line 3,805 ⟶ 4,736:
 
Uses the same library as Perl, so comes with the same caveats.
<syntaxhighlight lang="raku" perl6line>use Math::Polynomial::Cyclotomic:from<Perl5> <cyclo_poly_iterate cyclo_poly>;
 
say 'First 30 cyclotomic polynomials:';
Line 3,828 ⟶ 4,759:
sub super ($str) {
$str.subst( / '^' (\d+) /, { $0.trans([<0123456789>.comb] => [<⁰¹²³⁴⁵⁶⁷⁸⁹>.comb]) }, :g)
}</langsyntaxhighlight>
<pre>First 30 cyclotomic polynomials:
Φ(1) = (x - 1)
Line 3,873 ⟶ 4,804:
 
=={{header|Sidef}}==
Built-in:
Solution based on polynomial interpolation (slow).
<syntaxhighlight lang="ruby">say "First 30 cyclotomic polynomials:"
<lang ruby>var Poly = require('Math::Polynomial')
Poly.string_config(Hash(fold_sign => true, prefix => "", suffix => ""))
 
func poly_interpolation(v) {
v.len.of {|n| v.len.of {|k| n**k } }.msolve(v)
}
 
say "First 30 cyclotomic polynomials:"
for k in (1..30) {
var a =say ("Φ(#{k+1}).of {= ", cyclotomic(k, _) })
var Φ = poly_interpolation(a)
say ("Φ(#{k}) = ", Poly.new(Φ...))
}
 
say "\nSmallest cyclotomic polynomial with n or -n as a coefficient:"
for n in (1..10) { # very slow
var k = (1..Inf -> first {|k|
poly_interpolation(cyclotomic(k+1).ofcoeffs.any { cyclotomic(k, _) }).first { tail.abs == n }
})
say "Φ(#{k}) has coefficient with magnitude #{n}"
}</langsyntaxhighlight>
 
Slightly faster solution, using the '''Math::Polynomial::Cyclotomic''' Perl module.
<lang ruby>var Poly = require('Math::Polynomial')
require('Math::Polynomial::Cyclotomic')
 
Poly.string_config(Hash(fold_sign => true, prefix => "", suffix => ""))
 
say "First 30 cyclotomic polynomials:"
for k in (1..30) {
say ("Φ(#{k}) = ", Poly.new.cyclotomic(k))
}
 
say "\nSmallest cyclotomic polynomial with n or -n as a coefficient:"
for n in (1..10) {
var p = Poly.new
var k = (1..Inf -> first {|k|
[p.cyclotomic(k).coeff].first { .abs == n }
})
say "Φ(#{k}) has coefficient with magnitude = #{n}"
}</lang>
 
{{out}}
Line 3,960 ⟶ 4,862:
^C
</pre>
 
=={{header|Visual Basic .NET}}==
{{trans|C++}}
<langsyntaxhighlight lang="vbnet">Imports System.Text
 
Module Module1
Line 4,444 ⟶ 5,347:
End Sub
 
End Module</langsyntaxhighlight>
{{out}}
<pre>Task 1: cyclotomic polynomials for n <= 30:
Line 4,489 ⟶ 5,392:
CP[6545] has coefficient with magnitude = 9
CP[10465] has coefficient with magnitude = 10</pre>
 
=={{header|Wren}}==
===Version 1===
{{trans|Go}}
{{libheader|Wren-iterate}}
{{libheader|Wren-sort}}
{{libheader|Wren-math}}
{{libheader|Wren-fmt}}
Second part is very slow. Limited to first 7 to finish in a reasonable time - 5 minutes on my machine.
<syntaxhighlight lang="wren">import "./iterate" for Stepped
import "./sort" for Sort
import "./math" for Int, Nums
import "./fmt" for Fmt
 
var algo = 2
var maxAllFactors = 1e5
 
class Term {
construct new(coef, exp) {
_coef = coef
_exp = exp
}
 
coef { _coef }
exp { _exp }
 
*(t) { Term.new(_coef * t.coef, _exp + t.exp) }
 
+(t) {
if (_exp != t.exp) Fiber.abort("Exponents unequal in term '+' method.")
return Term.new(_coef + t.coef, _exp)
}
 
- { Term.new(-_coef, _exp) }
 
toString {
if (_coef == 0) return "0"
if (_exp == 0) return _coef.toString
if (_coef == 1) return (_exp == 1) ? "x" : "x^%(_exp)"
if (_exp == 1) return "%(_coef)x"
return "%(_coef)x^%(_exp)"
}
}
 
class Poly {
// pass coef, exp in pairs as parameters
construct new(values) {
var le = values.count
if (le == 0) {
_terms = [Term.new(0, 0)]
} else {
if (le%2 != 0) Fiber.abort("Odd number of parameters(%(le)) passed to Poly constructor.")
_terms = []
for (i in Stepped.new(0...le, 2)) _terms.add(Term.new(values[i], values[i+1]))
tidy()
}
}
 
terms { _terms }
 
hasCoefAbs(coef) { _terms.any { |t| t.coef.abs == coef } }
 
+(p2) {
var p3 = Poly.new([])
var le = _terms.count
var le2 = p2.terms.count
while (le > 0 || le2 > 0) {
if (le == 0) {
p3.terms.add(p2.terms[le2-1])
le2 = le2 - 1
} else if (le2 == 0) {
p3.terms.add(_terms[le-1])
le = le - 1
} else {
var t = _terms[le-1]
var t2 = p2.terms[le2-1]
if (t.exp == t2.exp) {
var t3 = t + t2
if (t3.coef != 0) p3.terms.add(t3)
le = le - 1
le2 = le2 - 1
} else if (t.exp < t2.exp) {
p3.terms.add(t)
le = le - 1
} else {
p3.terms.add(t2)
le2 = le2 - 1
}
}
}
p3.tidy()
return p3
}
 
addTerm(t) {
var q = Poly.new([])
var added = false
for (i in 0..._terms.count) {
var ct = _terms[i]
if (ct.exp == t.exp) {
added = true
if (ct.coef + t.coef != 0) q.terms.add(ct + t)
} else {
q.terms.add(ct)
}
}
if (!added) q.terms.add(t)
q.tidy()
return q
}
 
mulTerm(t) {
var q = Poly.new([])
for (i in 0..._terms.count) {
var ct = _terms[i]
q.terms.add(ct * t)
}
q.tidy()
return q
}
 
/(v) {
var p = this
var q = Poly.new([])
var lcv = v.leadingCoef
var dv = v.degree
while (p.degree >= v.degree) {
var lcp = p.leadingCoef
var s = (lcp/lcv).truncate
var t = Term.new(s, p.degree - dv)
q = q.addTerm(t)
p = p + v.mulTerm(-t)
}
q.tidy()
return q
}
 
leadingCoef { _terms[0].coef }
 
degree { _terms[0].exp }
 
toString {
var sb = ""
var first = true
for (t in _terms) {
if (first) {
sb = sb + t.toString
first = false
} else {
sb = sb + " "
if (t.coef > 0) {
sb = sb + "+ "
sb = sb + t.toString
} else {
sb = sb + "- "
sb = sb + (-t).toString
}
}
}
return sb
}
 
// in place descending sort by term.exp
sortTerms() {
var cmp = Fn.new { |t1, t2| (t2.exp - t1.exp).sign }
Sort.quick(_terms, 0, _terms.count-1, cmp)
}
 
// sort terms and remove any unnecesary zero terms
tidy() {
sortTerms()
if (degree > 0) {
for (i in _terms.count-1..0) {
if (_terms[i].coef == 0) _terms.removeAt(i)
}
if (_terms.count == 0) _terms.add(Term.new(0, 0))
}
}
}
 
var computed = {}
var allFactors = {2: {2: 1}}
 
var getFactors // recursive function
getFactors = Fn.new { |n|
var f = allFactors[n]
if (f) return f
var factors = {}
if (n%2 == 0) {
var factorsDivTwo = getFactors.call(n/2)
for (me in factorsDivTwo) factors[me.key] = me.value
factors[2] = factors[2] ? factors[2] + 1 : 1
if (n < maxAllFactors) allFactors[n] = factors
return factors
}
var prime = true
var sqrt = n.sqrt.floor
var i = 3
while (i <= sqrt){
if (n%i == 0) {
prime = false
for (me in getFactors.call(n/i)) factors[me.key] = me.value
factors[i] = factors[i] ? factors[i] + 1 : 1
if (n < maxAllFactors) allFactors[n] = factors
return factors
}
i = i + 2
}
if (prime) {
factors[n] = 1
if (n < maxAllFactors) allFactors[n] = factors
}
return factors
}
 
var cycloPoly // recursive function
cycloPoly = Fn.new { |n|
var p = computed[n]
if (p) return p
if (n == 1) {
// polynomialL x - 1
p = Poly.new([1, 1, -1, 0])
computed[1] = p
return p
}
var factors = getFactors.call(n)
var cyclo = Poly.new([])
if (factors[n]) {
// n is prime
for (i in 0...n) cyclo.terms.add(Term.new(1, i))
} else if (factors.count == 2 && factors[2] == 1 && factors[n/2] == 1) {
// n == 2p
var prime = n / 2
var coef = -1
for (i in 0...prime) {
coef = coef * (-1)
cyclo.terms.add(Term.new(coef, i))
}
} else if (factors.count == 1) {
var h = factors[2]
if (h) { // n == 2^h
cyclo.terms.addAll([Term.new(1, 1 << (h-1)), Term.new(1, 0)])
} else if (!factors[n]) {
// n == p ^ k
var p = 0
for (prime in factors.keys) p = prime
var k = factors[p]
for (i in 0...p) {
var pk = p.pow(k-1).floor
cyclo.terms.add(Term.new(1, i * pk))
}
}
} else if (factors.count == 2 && factors[2]) {
// n = 2^h * p^k
var p = 0
for (prime in factors.keys) if (prime != 2) p = prime
var coef = -1
var twoExp = 1 << (factors[2] - 1)
var k = factors[p]
for (i in 0...p) {
coef = coef * (-1)
var pk = p.pow(k-1).floor
cyclo.terms.add(Term.new(coef, i * twoExp * pk))
}
} else if (factors[2] && (n/2) % 2 == 1 && (n/2) > 1) {
// CP(2m)[x] == CP(-m)[x], n odd integer > 1
var cycloDiv2 = cycloPoly.call(n/2)
for (t in cycloDiv2.terms) {
var t2 = t
if (t.exp % 2 != 0) t2 = -t
cyclo.terms.add(t2)
}
} else if (algo == 0) {
// slow - uses basic definition
var divs = Int.properDivisors(n)
// polynomial: x^n - 1
var cyclo = Poly.new([1, n, -1, 0])
for (i in divs) {
var p = cycloPoly.call(i)
cyclo = cyclo / p
}
} else if (algo == 1) {
// faster - remove max divisor (and all divisors of max divisor)
// only one divide for all divisors of max divisor
var divs = Int.properDivisors(n)
var maxDiv = Nums.max(divs)
var divsExceptMax = divs.where { |d| maxDiv % d != 0 }.toList
// polynomial: ( x^n - 1 ) / ( x^m - 1 ), where m is the max divisor
cyclo = Poly.new([1, n, -1, 0])
cyclo = cyclo / Poly.new([1, maxDiv, -1, 0])
for (i in divsExceptMax) {
var p = cycloPoly.call(i)
cyclo = cyclo / p
}
} else if (algo == 2) {
// fastest
// let p, q be primes such that p does not divide n, and q divides n
// then CP(np)[x] = CP(n)[x^p] / CP(n)[x]
var m = 1
cyclo = cycloPoly.call(m)
var primes = []
for (prime in factors.keys) primes.add(prime)
Sort.quick(primes)
for (prime in primes) {
// CP(m)[x]
var cycloM = cyclo
// compute CP(m)[x^p]
var terms = []
for (t in cycloM.terms) terms.add(Term.new(t.coef, t.exp * prime))
cyclo = Poly.new([])
cyclo.terms.addAll(terms)
cyclo.tidy()
cyclo = cyclo / cycloM
m = m * prime
}
// now, m is the largest square free divisor of n
var s = n / m
// Compute CP(n)[x] = CP(m)[x^s]
var terms = []
for (t in cyclo.terms) terms.add(Term.new(t.coef, t.exp * s))
cyclo = Poly.new([])
cyclo.terms.addAll(terms)
} else {
Fiber.abort("Invalid algorithm.")
}
cyclo.tidy()
computed[n] = cyclo
return cyclo
}
 
System.print("Task 1: cyclotomic polynomials for n <= 30:")
for (i in 1..30) {
var p = cycloPoly.call(i)
Fmt.print("CP[$2d] = $s", i, p)
}
 
System.print("\nTask 2: Smallest cyclotomic polynomial with n or -n as a coefficient:")
var n = 0
for (i in 1..7) {
while(true) {
n = n + 1
var cyclo = cycloPoly.call(n)
if (cyclo.hasCoefAbs(i)) {
Fmt.print("CP[$d] has coefficient with magnitude = $d", n, i)
n = n - 1
break
}
}
}</syntaxhighlight>
 
{{out}}
<pre>
Task 1: cyclotomic polynomials for n <= 30:
CP[ 1] = x - 1
CP[ 2] = x + 1
CP[ 3] = x^2 + x + 1
CP[ 4] = x^2 + 1
CP[ 5] = x^4 + x^3 + x^2 + x + 1
CP[ 6] = x^2 - x + 1
CP[ 7] = x^6 + x^5 + x^4 + x^3 + x^2 + x + 1
CP[ 8] = x^4 + 1
CP[ 9] = x^6 + x^3 + 1
CP[10] = x^4 - x^3 + x^2 - x + 1
CP[11] = x^10 + x^9 + x^8 + x^7 + x^6 + x^5 + x^4 + x^3 + x^2 + x + 1
CP[12] = x^4 - x^2 + 1
CP[13] = x^12 + x^11 + x^10 + x^9 + x^8 + x^7 + x^6 + x^5 + x^4 + x^3 + x^2 + x + 1
CP[14] = x^6 - x^5 + x^4 - x^3 + x^2 - x + 1
CP[15] = x^8 - x^7 + x^5 - x^4 + x^3 - x + 1
CP[16] = x^8 + 1
CP[17] = x^16 + x^15 + x^14 + x^13 + x^12 + x^11 + x^10 + x^9 + x^8 + x^7 + x^6 + x^5 + x^4 + x^3 + x^2 + x + 1
CP[18] = x^6 - x^3 + 1
CP[19] = x^18 + x^17 + x^16 + x^15 + x^14 + x^13 + x^12 + x^11 + x^10 + x^9 + x^8 + x^7 + x^6 + x^5 + x^4 + x^3 + x^2 + x + 1
CP[20] = x^8 - x^6 + x^4 - x^2 + 1
CP[21] = x^12 - x^11 + x^9 - x^8 + x^6 - x^4 + x^3 - x + 1
CP[22] = x^10 - x^9 + x^8 - x^7 + x^6 - x^5 + x^4 - x^3 + x^2 - x + 1
CP[23] = x^22 + x^21 + x^20 + x^19 + x^18 + x^17 + x^16 + x^15 + x^14 + x^13 + x^12 + x^11 + x^10 + x^9 + x^8 + x^7 + x^6 + x^5 + x^4 + x^3 + x^2 + x + 1
CP[24] = x^8 - x^4 + 1
CP[25] = x^20 + x^15 + x^10 + x^5 + 1
CP[26] = x^12 - x^11 + x^10 - x^9 + x^8 - x^7 + x^6 - x^5 + x^4 - x^3 + x^2 - x + 1
CP[27] = x^18 + x^9 + 1
CP[28] = x^12 - x^10 + x^8 - x^6 + x^4 - x^2 + 1
CP[29] = x^28 + x^27 + x^26 + x^25 + x^24 + x^23 + x^22 + x^21 + x^20 + x^19 + x^18 + x^17 + x^16 + x^15 + x^14 + x^13 + x^12 + x^11 + x^10 + x^9 + x^8 + x^7 + x^6 + x^5 + x^4 + x^3 + x^2 + x + 1
CP[30] = x^8 + x^7 - x^5 - x^4 - x^3 + x + 1
 
Task 2: Smallest cyclotomic polynomial with n or -n as a coefficient:
CP[1] has coefficient with magnitude = 1
CP[105] has coefficient with magnitude = 2
CP[385] has coefficient with magnitude = 3
CP[1365] has coefficient with magnitude = 4
CP[1785] has coefficient with magnitude = 5
CP[2805] has coefficient with magnitude = 6
CP[3135] has coefficient with magnitude = 7
</pre>
 
===Version 2===
{{trans|Java}}
A translation of the alternative version which completes the second part in about 33 seconds.
<syntaxhighlight lang="wren">import "./math" for Int
import "./fmt" for Fmt
 
class CP {
// Return the Cyclotomic Polynomial of order 'cpIndex' as a list of coefficients,
// where, for example, the polynomial 3x^2 - 1 is represented by the list [3, 0, -1].
static cycloPoly(cpIndex) {
var polynomial = [1, -1]
if (cpIndex == 1) return polynomial
if (Int.isPrime(cpIndex)) return List.filled(cpIndex, 1)
var primes = Int.distinctPrimeFactors(cpIndex)
var product = 1
for (prime in primes) {
var numerator = substituteExponent(polynomial, prime)
polynomial = exactDivision(numerator, polynomial)
product = product * prime
}
return substituteExponent(polynomial, Int.quo(cpIndex, product))
}
 
// Return the Cyclotomic Polynomial obtained from 'polynomial'
// by replacing x with x^'exponent'.
static substituteExponent(polynomial, exponent) {
var result = List.filled(exponent * (polynomial.count - 1) + 1, 0)
for (i in polynomial.count-1..0) result[i*exponent] = polynomial[i]
return result
}
 
// Return the Cyclotomic Polynomial equal to 'dividend' / 'divisor'.
// The division is always exact.
static exactDivision(dividend, divisor) {
var result = dividend.toList
for (i in 0..dividend.count - divisor.count) {
if (result[i] != 0) {
for (j in 1...divisor.count) {
result[i+j] = result[i+j] - divisor[j] * result[i]
}
}
}
return result[0..result.count - divisor.count]
}
 
// Return whether 'polynomial' has a coefficient of equal magnitude
// to 'coefficient'.
static hasHeight(polynomial, coefficient) {
for (i in 0..Int.quo(polynomial.count + 1, 2)) {
if (polynomial[i].abs == coefficient) return true
}
return false
}
}
 
System.print("Task 1: Cyclotomic polynomials for n <= 30:")
for (cpIndex in 1..30) {
Fmt.write("CP[$2d] = ", cpIndex)
Fmt.pprint("$d", CP.cycloPoly(cpIndex), "", "x")
}
 
System.print("\nTask 2: Smallest cyclotomic polynomial with n or -n as a coefficient:")
System.print("CP[ 1] has a coefficient with magnitude 1")
var cpIndex = 2
for (coeff in 2..10) {
while (Int.isPrime(cpIndex) || !CP.hasHeight(CP.cycloPoly(cpIndex), coeff)) {
cpIndex = cpIndex + 1
}
Fmt.print("CP[$5d] has a coefficient with magnitude $d", cpIndex, coeff)
}</syntaxhighlight>
 
{{out}}
<pre>
Task 1: Cyclotomic polynomials for n <= 30:
CP[ 1] = x - 1
CP[ 2] = x + 1
CP[ 3] = x² + x + 1
CP[ 4] = x² + 1
CP[ 5] = x⁴ + x³ + x² + x + 1
CP[ 6] = x² - x + 1
CP[ 7] = x⁶ + x⁵ + x⁴ + x³ + x² + x + 1
CP[ 8] = x⁴ + 1
CP[ 9] = x⁶ + x³ + 1
CP[10] = x⁴ - x³ + x² - x + 1
CP[11] = x¹⁰ + x⁹ + x⁸ + x⁷ + x⁶ + x⁵ + x⁴ + x³ + x² + x + 1
CP[12] = x⁴ - x² + 1
CP[13] = x¹² + x¹¹ + x¹⁰ + x⁹ + x⁸ + x⁷ + x⁶ + x⁵ + x⁴ + x³ + x² + x + 1
CP[14] = x⁶ - x⁵ + x⁴ - x³ + x² - x + 1
CP[15] = x⁸ - x⁷ + x⁵ - x⁴ + x³ - x + 1
CP[16] = x⁸ + 1
CP[17] = x¹⁶ + x¹⁵ + x¹⁴ + x¹³ + x¹² + x¹¹ + x¹⁰ + x⁹ + x⁸ + x⁷ + x⁶ + x⁵ + x⁴ + x³ + x² + x + 1
CP[18] = x⁶ - x³ + 1
CP[19] = x¹⁸ + x¹⁷ + x¹⁶ + x¹⁵ + x¹⁴ + x¹³ + x¹² + x¹¹ + x¹⁰ + x⁹ + x⁸ + x⁷ + x⁶ + x⁵ + x⁴ + x³ + x² + x + 1
CP[20] = x⁸ - x⁶ + x⁴ - x² + 1
CP[21] = x¹² - x¹¹ + x⁹ - x⁸ + x⁶ - x⁴ + x³ - x + 1
CP[22] = x¹⁰ - x⁹ + x⁸ - x⁷ + x⁶ - x⁵ + x⁴ - x³ + x² - x + 1
CP[23] = x²² + x²¹ + x²⁰ + x¹⁹ + x¹⁸ + x¹⁷ + x¹⁶ + x¹⁵ + x¹⁴ + x¹³ + x¹² + x¹¹ + x¹⁰ + x⁹ + x⁸ + x⁷ + x⁶ + x⁵ + x⁴ + x³ + x² + x + 1
CP[24] = x⁸ - x⁴ + 1
CP[25] = x²⁰ + x¹⁵ + x¹⁰ + x⁵ + 1
CP[26] = x¹² - x¹¹ + x¹⁰ - x⁹ + x⁸ - x⁷ + x⁶ - x⁵ + x⁴ - x³ + x² - x + 1
CP[27] = x¹⁸ + x⁹ + 1
CP[28] = x¹² - x¹⁰ + x⁸ - x⁶ + x⁴ - x² + 1
CP[29] = x²⁸ + x²⁷ + x²⁶ + x²⁵ + x²⁴ + x²³ + x²² + x²¹ + x²⁰ + x¹⁹ + x¹⁸ + x¹⁷ + x¹⁶ + x¹⁵ + x¹⁴ + x¹³ + x¹² + x¹¹ + x¹⁰ + x⁹ + x⁸ + x⁷ + x⁶ + x⁵ + x⁴ + x³ + x² + x + 1
CP[30] = x⁸ + x⁷ - x⁵ - x⁴ - x³ + x + 1
 
Task 2: Smallest cyclotomic polynomial with n or -n as a coefficient:
CP[ 1] has a coefficient with magnitude 1
CP[ 105] has a coefficient with magnitude 2
CP[ 385] has a coefficient with magnitude 3
CP[ 1365] has a coefficient with magnitude 4
CP[ 1785] has a coefficient with magnitude 5
CP[ 2805] has a coefficient with magnitude 6
CP[ 3135] has a coefficient with magnitude 7
CP[ 6545] has a coefficient with magnitude 8
CP[ 6545] has a coefficient with magnitude 9
CP[10465] has a coefficient with magnitude 10
</pre>
2,442

edits