-
Notifications
You must be signed in to change notification settings - Fork 679
/
Copy pathp041.mathematica
30 lines (27 loc) · 967 Bytes
/
p041.mathematica
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
(*
* Solution to Project Euler problem 41
* Copyright (c) Project Nayuki. All rights reserved.
*
* https://www.nayuki.io/page/project-euler-solutions
* https://github.com/nayuki/Project-Euler-solutions
*)
PrevPermutation[s_] := Block[{i, j},
(* Find non-decreasing suffix. e.g.: 1 3 [2 2 4 5] *)
For[i = Length[s], i > 1 && s[[i - 1]] <= s[[i]], i--];
(* i is the index of the head of such suffix *)
If[i <= 1, Abort[]];
(* Find latest element that is less than s[i - 1] *)
For[j = Length[s], s[[j]] >= s[[i - 1]], j--];
(* Return new list with indexes i and j swapped, followed by the suffix reversed *)
Join[Take[s, i - 2], {s[[j]]}, Reverse[Drop[ReplacePart[s, s[[i - 1]], j], i - 1]]]]
ans = "Not found";
For[n = 9, n >= 1, n--,
perm = Range[n, 1, -1];
While[True,
If[PrimeQ[FromDigits[perm]],
ans = FromDigits[perm];
n = 0;
Break[]];
If[perm == Range[n], Break[]];
perm = PrevPermutation[perm];]]
ans