Fundamental Solution of the Pell Equation
$begingroup$
Given some positive integer $n$ that is not a square, find the fundamental solution $(x,y)$ of the associated Pell equation
$$x^2 - ncdot y^2 = 1$$
Details
- The fundamental $(x,y)$ is a pair of integers $x,y$ satisfying the equation where $x$ is minimal, and positive. (There is always the trivial solution $(x,y)=(1,0)$ which is not counted.)
- You can assume that $n$ is not a square.
Examples
n x y
1 - -
2 3 2
3 2 1
4 - -
5 9 4
6 5 2
7 8 3
8 3 1
9 - -
10 19 6
11 10 3
12 7 2
13 649 180
14 15 4
15 4 1
16 - -
17 33 8
18 17 4
19 170 39
20 9 2
21 55 12
22 197 42
23 24 5
24 5 1
25 - -
26 51 10
27 26 5
28 127 24
29 9801 1820
30 11 2
31 1520 273
32 17 3
33 23 4
34 35 6
35 6 1
36 - -
37 73 12
38 37 6
39 25 4
40 19 3
41 2049 320
42 13 2
43 3482 531
44 199 30
45 161 24
46 24335 3588
47 48 7
48 7 1
49 - -
50 99 14
51 50 7
52 649 90
53 66249 9100
54 485 66
55 89 12
56 15 2
57 151 20
58 19603 2574
59 530 69
60 31 4
61 1766319049 226153980
62 63 8
63 8 1
64 - -
65 129 16
66 65 8
67 48842 5967
68 33 4
69 7775 936
70 251 30
71 3480 413
72 17 2
73 2281249 267000
74 3699 430
75 26 3
76 57799 6630
77 351 40
78 53 6
79 80 9
80 9 1
81 - -
82 163 18
83 82 9
84 55 6
85 285769 30996
86 10405 1122
87 28 3
88 197 21
89 500001 53000
90 19 2
91 1574 165
92 1151 120
93 12151 1260
94 2143295 221064
95 39 4
96 49 5
97 62809633 6377352
98 99 10
99 10 1
Relevant OEIS sequences: A002350 A002349 A033313 A033317
code-golf math number-theory abstract-algebra polynomials
$endgroup$
add a comment |
$begingroup$
Given some positive integer $n$ that is not a square, find the fundamental solution $(x,y)$ of the associated Pell equation
$$x^2 - ncdot y^2 = 1$$
Details
- The fundamental $(x,y)$ is a pair of integers $x,y$ satisfying the equation where $x$ is minimal, and positive. (There is always the trivial solution $(x,y)=(1,0)$ which is not counted.)
- You can assume that $n$ is not a square.
Examples
n x y
1 - -
2 3 2
3 2 1
4 - -
5 9 4
6 5 2
7 8 3
8 3 1
9 - -
10 19 6
11 10 3
12 7 2
13 649 180
14 15 4
15 4 1
16 - -
17 33 8
18 17 4
19 170 39
20 9 2
21 55 12
22 197 42
23 24 5
24 5 1
25 - -
26 51 10
27 26 5
28 127 24
29 9801 1820
30 11 2
31 1520 273
32 17 3
33 23 4
34 35 6
35 6 1
36 - -
37 73 12
38 37 6
39 25 4
40 19 3
41 2049 320
42 13 2
43 3482 531
44 199 30
45 161 24
46 24335 3588
47 48 7
48 7 1
49 - -
50 99 14
51 50 7
52 649 90
53 66249 9100
54 485 66
55 89 12
56 15 2
57 151 20
58 19603 2574
59 530 69
60 31 4
61 1766319049 226153980
62 63 8
63 8 1
64 - -
65 129 16
66 65 8
67 48842 5967
68 33 4
69 7775 936
70 251 30
71 3480 413
72 17 2
73 2281249 267000
74 3699 430
75 26 3
76 57799 6630
77 351 40
78 53 6
79 80 9
80 9 1
81 - -
82 163 18
83 82 9
84 55 6
85 285769 30996
86 10405 1122
87 28 3
88 197 21
89 500001 53000
90 19 2
91 1574 165
92 1151 120
93 12151 1260
94 2143295 221064
95 39 4
96 49 5
97 62809633 6377352
98 99 10
99 10 1
Relevant OEIS sequences: A002350 A002349 A033313 A033317
code-golf math number-theory abstract-algebra polynomials
$endgroup$
$begingroup$
Surprised that there isn't any challenge with the Pell equation yet, since it's pretty well-known I thought. At least, I do remember using it sometimes with Project Euler challenges.
$endgroup$
– Kevin Cruijssen
yesterday
$begingroup$
@Fatalize "You can assume that $n$ is not a square." Would probably be clearer if the test cases omitted those imho, though.
$endgroup$
– Kevin Cruijssen
yesterday
1
$begingroup$
@KevinCruijssen I considered that, but I thought it would be more confusing to omit some of then
s. (btw I was also surprized but I had this challenge in the sandbox for about a year)
$endgroup$
– flawr
yesterday
add a comment |
$begingroup$
Given some positive integer $n$ that is not a square, find the fundamental solution $(x,y)$ of the associated Pell equation
$$x^2 - ncdot y^2 = 1$$
Details
- The fundamental $(x,y)$ is a pair of integers $x,y$ satisfying the equation where $x$ is minimal, and positive. (There is always the trivial solution $(x,y)=(1,0)$ which is not counted.)
- You can assume that $n$ is not a square.
Examples
n x y
1 - -
2 3 2
3 2 1
4 - -
5 9 4
6 5 2
7 8 3
8 3 1
9 - -
10 19 6
11 10 3
12 7 2
13 649 180
14 15 4
15 4 1
16 - -
17 33 8
18 17 4
19 170 39
20 9 2
21 55 12
22 197 42
23 24 5
24 5 1
25 - -
26 51 10
27 26 5
28 127 24
29 9801 1820
30 11 2
31 1520 273
32 17 3
33 23 4
34 35 6
35 6 1
36 - -
37 73 12
38 37 6
39 25 4
40 19 3
41 2049 320
42 13 2
43 3482 531
44 199 30
45 161 24
46 24335 3588
47 48 7
48 7 1
49 - -
50 99 14
51 50 7
52 649 90
53 66249 9100
54 485 66
55 89 12
56 15 2
57 151 20
58 19603 2574
59 530 69
60 31 4
61 1766319049 226153980
62 63 8
63 8 1
64 - -
65 129 16
66 65 8
67 48842 5967
68 33 4
69 7775 936
70 251 30
71 3480 413
72 17 2
73 2281249 267000
74 3699 430
75 26 3
76 57799 6630
77 351 40
78 53 6
79 80 9
80 9 1
81 - -
82 163 18
83 82 9
84 55 6
85 285769 30996
86 10405 1122
87 28 3
88 197 21
89 500001 53000
90 19 2
91 1574 165
92 1151 120
93 12151 1260
94 2143295 221064
95 39 4
96 49 5
97 62809633 6377352
98 99 10
99 10 1
Relevant OEIS sequences: A002350 A002349 A033313 A033317
code-golf math number-theory abstract-algebra polynomials
$endgroup$
Given some positive integer $n$ that is not a square, find the fundamental solution $(x,y)$ of the associated Pell equation
$$x^2 - ncdot y^2 = 1$$
Details
- The fundamental $(x,y)$ is a pair of integers $x,y$ satisfying the equation where $x$ is minimal, and positive. (There is always the trivial solution $(x,y)=(1,0)$ which is not counted.)
- You can assume that $n$ is not a square.
Examples
n x y
1 - -
2 3 2
3 2 1
4 - -
5 9 4
6 5 2
7 8 3
8 3 1
9 - -
10 19 6
11 10 3
12 7 2
13 649 180
14 15 4
15 4 1
16 - -
17 33 8
18 17 4
19 170 39
20 9 2
21 55 12
22 197 42
23 24 5
24 5 1
25 - -
26 51 10
27 26 5
28 127 24
29 9801 1820
30 11 2
31 1520 273
32 17 3
33 23 4
34 35 6
35 6 1
36 - -
37 73 12
38 37 6
39 25 4
40 19 3
41 2049 320
42 13 2
43 3482 531
44 199 30
45 161 24
46 24335 3588
47 48 7
48 7 1
49 - -
50 99 14
51 50 7
52 649 90
53 66249 9100
54 485 66
55 89 12
56 15 2
57 151 20
58 19603 2574
59 530 69
60 31 4
61 1766319049 226153980
62 63 8
63 8 1
64 - -
65 129 16
66 65 8
67 48842 5967
68 33 4
69 7775 936
70 251 30
71 3480 413
72 17 2
73 2281249 267000
74 3699 430
75 26 3
76 57799 6630
77 351 40
78 53 6
79 80 9
80 9 1
81 - -
82 163 18
83 82 9
84 55 6
85 285769 30996
86 10405 1122
87 28 3
88 197 21
89 500001 53000
90 19 2
91 1574 165
92 1151 120
93 12151 1260
94 2143295 221064
95 39 4
96 49 5
97 62809633 6377352
98 99 10
99 10 1
Relevant OEIS sequences: A002350 A002349 A033313 A033317
code-golf math number-theory abstract-algebra polynomials
code-golf math number-theory abstract-algebra polynomials
asked yesterday
flawrflawr
27.3k667192
27.3k667192
$begingroup$
Surprised that there isn't any challenge with the Pell equation yet, since it's pretty well-known I thought. At least, I do remember using it sometimes with Project Euler challenges.
$endgroup$
– Kevin Cruijssen
yesterday
$begingroup$
@Fatalize "You can assume that $n$ is not a square." Would probably be clearer if the test cases omitted those imho, though.
$endgroup$
– Kevin Cruijssen
yesterday
1
$begingroup$
@KevinCruijssen I considered that, but I thought it would be more confusing to omit some of then
s. (btw I was also surprized but I had this challenge in the sandbox for about a year)
$endgroup$
– flawr
yesterday
add a comment |
$begingroup$
Surprised that there isn't any challenge with the Pell equation yet, since it's pretty well-known I thought. At least, I do remember using it sometimes with Project Euler challenges.
$endgroup$
– Kevin Cruijssen
yesterday
$begingroup$
@Fatalize "You can assume that $n$ is not a square." Would probably be clearer if the test cases omitted those imho, though.
$endgroup$
– Kevin Cruijssen
yesterday
1
$begingroup$
@KevinCruijssen I considered that, but I thought it would be more confusing to omit some of then
s. (btw I was also surprized but I had this challenge in the sandbox for about a year)
$endgroup$
– flawr
yesterday
$begingroup$
Surprised that there isn't any challenge with the Pell equation yet, since it's pretty well-known I thought. At least, I do remember using it sometimes with Project Euler challenges.
$endgroup$
– Kevin Cruijssen
yesterday
$begingroup$
Surprised that there isn't any challenge with the Pell equation yet, since it's pretty well-known I thought. At least, I do remember using it sometimes with Project Euler challenges.
$endgroup$
– Kevin Cruijssen
yesterday
$begingroup$
@Fatalize "You can assume that $n$ is not a square." Would probably be clearer if the test cases omitted those imho, though.
$endgroup$
– Kevin Cruijssen
yesterday
$begingroup$
@Fatalize "You can assume that $n$ is not a square." Would probably be clearer if the test cases omitted those imho, though.
$endgroup$
– Kevin Cruijssen
yesterday
1
1
$begingroup$
@KevinCruijssen I considered that, but I thought it would be more confusing to omit some of the
n
s. (btw I was also surprized but I had this challenge in the sandbox for about a year)$endgroup$
– flawr
yesterday
$begingroup$
@KevinCruijssen I considered that, but I thought it would be more confusing to omit some of the
n
s. (btw I was also surprized but I had this challenge in the sandbox for about a year)$endgroup$
– flawr
yesterday
add a comment |
21 Answers
21
active
oldest
votes
$begingroup$
Piet, 612 codels
Takes n from standard input. Outputs y then x, space-separated.
Codel size 1:
Codel size 4, for easier viewing:
Explanation
Check out this NPiet trace, which shows the program calculating the solution for an input value of 99.
I'm not sure whether I'd ever heard of Pell's equation before this challenge, so I got all of the following from Wikipedia; specifically, these sections of three articles:
- Pell's equation § Fundamental solution via continued fractions
- Methods of computing square roots § Continued fraction expansion
- Continued fraction § Infinite continued fractions and convergents
Basically, what we do is this:
- Get $n$ from standard input.
- Find $lfloorsqrt nrfloor$ by incrementing a counter until its square exceeds $n$, then decrement it once. (This is the first loop you can see in the trace, at top left.)
- Set up some variables for calculating $x$ and $y$ from the continued fraction of $sqrt n$.
- Check whether $x$ and $y$ fit Pell's equation yet. If they do, output the values (this is the downwards branch about 2/3 of the way across) and then exit (by running into the red block at far left).
- If not, iteratively update the variables and go back to step 4. (This is the wide loop out to the right, back across the bottom, and rejoining not quite halfway across.)
I frankly have no idea whether or not a brute-force approach would be shorter, and I'm not about to try it! Okay, so I tried it.
$endgroup$
add a comment |
$begingroup$
Brachylog, 16 bytes
;1↔;Ċz×ᵐ-1∧Ċ√ᵐℕᵐ
Try it online!
Explanation
;1↔ Take the list [1, Input]
;Ċz Zip it with a couple of two unknown variables: [[1,I],[Input,J]]
×ᵐ Map multiply: [I, Input×J]
-1 I - Input×J must be equal to 1
∧ (and)
Ċ√ᵐ We are looking for the square roots of these two unknown variables
ℕᵐ And they must be natural numbers
(implicit attempt to find values that match those constraints)
$endgroup$
add a comment |
$begingroup$
Pari/GP, 36 bytes
PARI/GP almost has a built-in for this: quadunit
gives the fundamental unit of the quadratic field $mathbb{Q}(sqrt{D})$, where $D$ is the discriminant of the field. In other words, quadunit(4*n)
solves the Pell's equation $x^2 - n cdot y^2 = pm 1$. So I have to take the square when its norm is $-1$.
I don't know what algorithm it uses, but it even works when $n$ is not square-free.
Answers are given in the form x + y*w
, where w
denotes $sqrt{n}$.
n->if(norm(a=quadunit(4*n))>0,a,a^2)
Try it online!
$endgroup$
add a comment |
$begingroup$
Piet, 184 codels
This is the brute-force alternative I said (in my other answer) that I didn't want to write. It takes over 2 minutes to compute the solution for n = 13. I really don't want to try it on n = 29... but it checks out for every n up to 20, so I'm confident that it's correct.
Like that other answer, this takes n from standard input and outputs y then x, space-separated.
Codel size 1:
Codel size 4, for easier viewing:
Explanation
Here's the NPiet trace for an input value of 5.
This is the most brutal of brute force, iterating over both $x$ and $y$. Other solutions might iterate over $x$ and then calculate $y=sqrt{frac{x^2-1}{n}}$, but they're wimps.
Starting from $x=2$ and $y=1$, this checks whether $x$ and $y$ have solved the equation yet. If it has (the fork at the bottom near the right), it outputs the values and exits.
If not, it continues left, where $y$ is incremented and compared to $x$. (Then there's some direction-twiddling to follow the zig-zag path.)
This last comparison is where the path splits around the mid-left. If they're equal, $x$ is incremented and $y$ is set back to 1. And we go back to checking if it's a solution yet.
I still have some whitespace available, so maybe I'll see if I can incorporate that square-root calculation without enlarging the program.
$endgroup$
2
$begingroup$
Haha I agree about the wimps that use square roots :D
$endgroup$
– flawr
18 hours ago
add a comment |
$begingroup$
Wolfram Language (Mathematica), 46 bytes
FindInstance[x^2-y^2#==1&&x>1,{x,y},Integers]&
Try it online!
$endgroup$
1
$begingroup$
Is it assured that this always finds the fundamental solution?
$endgroup$
– Greg Martin
21 hours ago
$begingroup$
@GregMartin yes, it is.This always finds the first (minimum) solution. In this case this always returns {1,0}. That is why we have to choose x>1 and get the second (fundamental) solution
$endgroup$
– J42161217
16 hours ago
1
$begingroup$
I would like that to be true, but nothing in the documentation seems to indicate that....
$endgroup$
– Greg Martin
16 hours ago
$begingroup$
@GregMartin I have used this function many times and already knew how it worked. My only concern was to skip the first solution and that cost me those 5 extra bytes. You can easily write a program and test it (just to confirm millions of results)
$endgroup$
– J42161217
16 hours ago
add a comment |
$begingroup$
05AB1E, 17 16 14 bytes
Saved a byte thanks to Kevin Cruijssen.
Outputs [y, x]
∞.Δn*>t©1%_}®‚
Try it online!
Explanation
∞ # from the infinite list of numbers [1 ...]
.Δ } # find the first number that returns true under
n # square
* # multiply with input
> # increment
t© # sqrt (and save to register as potential x)
1% # modulus 1
_ # logical negation
®‚ # pair result (y) with register (x)
$endgroup$
$begingroup$
And you beat me to it again.. had a 17 byter as well, but it didn't work becauseŲ
is bugged with decimals.. >.< Anyway, you can remove both,
and add a trailing‚
(no, the comma's are not the same ;p) to save a byte.
$endgroup$
– Kevin Cruijssen
yesterday
$begingroup$
@KevinCruijssen: Thanks! Yeah I also went forŲ
first noticing that it didn't work as expected.
$endgroup$
– Emigna
yesterday
add a comment |
$begingroup$
Java 8, 74 73 72 bytes
n->{int x=1;var y=.1;for(;y%1>0;)y=Math.sqrt(-x*~++x/n);return x+" "+y;}
-1 byte thanks to @Arnauld.
-1 byte thanks to @OlivierGrégoire.
Try it online.
Explanation:
n->{ // Method with double parameter and string return-type
int x=1; // Integer `x`, starting at 1
var y=.1; // Double `y`, starting at 0.1
for(;y%1>0;) // Loop as long as `y` contains decimal digits:
y= // Set `y` to:
Math.sqrt( // The square-root of:
-x* // Negative `x`, multiplied by
~++x // `(-x-2)` (or `-(x+1)-1)` to be exact)
// (because we increase `x` by 1 first with `++x`)
/n); // Divided by the input
return x+" "+y;} // After the loop, return `x` and `y` with space-delimiter as result
$endgroup$
1
$begingroup$
72 bytes, by changingn
to adouble
, andx
to anint
, playing on the fact thatx*x-1
is equal to(-x-1)*(-x+1)
.
$endgroup$
– Olivier Grégoire
yesterday
$begingroup$
Well, I'm actually playing on the fact that(x+1)*(x+1)-1
is equal to-x*-(x+2)
, to be entirely correct.
$endgroup$
– Olivier Grégoire
yesterday
add a comment |
$begingroup$
R, 66 56 54 53 52 47 45 bytes
a full program
n=scan();while((x=(1+n*T^2)^.5)%%1)T=T+1;x;+T
-1 -2 thanks to @Giuseppe
-7 thanks to @Giuseppe & @Robin Ryder
-2 @JAD
$endgroup$
1
$begingroup$
use.5
instead of0.5
$endgroup$
– Giuseppe
yesterday
4
$begingroup$
46 bytes. Finding the smallest value ofx
is equivalent to finding the smallest value ofy
. This allows you to save 2 bytes because expressingx
in terms ofy
is shorter than the other way around, and 4 bytes by using the trick of usingT
which is initialized at 1.
$endgroup$
– Robin Ryder
yesterday
1
$begingroup$
@RobinRyder you might need a+T
at the end to make sure that wheny==1
it returns1
instead ofTRUE
but I'm not entirely sure.
$endgroup$
– Giuseppe
yesterday
2
$begingroup$
@Giuseppe Well spotted! You are right. That makes it 47 bytes
$endgroup$
– Robin Ryder
yesterday
1
$begingroup$
Seems to fail on n=61 (the silly large test case) due to big number issues. I think it's fine to allow for language limits, just noting the exception.
$endgroup$
– CriminallyVulgar
14 hours ago
|
show 5 more comments
$begingroup$
JavaScript (ES7), 47 bytes
n=>(g=x=>(y=((x*x-1)/n)**.5)%1?g(x+1):[x,y])(2)
Try it online!
Below is an alternate 49-byte version which keeps track of $x²-1$ directly instead of squaring $x$ at each iteration:
n=>[(g=x=>(y=(x/n)**.5)%1?1+g(x+=k+=2):2)(k=3),y]
Try it online!
Or we can go the non-recursive way for 50 bytes:
n=>eval('for(x=1;(y=((++x*x-1)/n)**.5)%1;);[x,y]')
Try it online!
$endgroup$
add a comment |
$begingroup$
MATL, 17 bytes
`@:Ut!G*-!1=&fts~
Try it online!
Explanation
The code keeps increasing a counter k = 1, 2, 3, ... For each k, solutions x, y with 1 ≤ x ≤ k, 1 ≤ y ≤ k are searched. The process when some solution if found.
This procedure is guaranteed to find only one solution, which is precisely the fundamental one. To see why, note that
- Any solution x>0, y>0 for n>1 satisfies x>y.
- If x,y is a solution and x',y' is a different solution then necessarily x≠x' and y≠y'.
As a consequence of 1 and 2,
- When the procedure stops at a given k, only one solution exists for that k, because if there were two solutions one of them would been found earlier, and the process would have stopped with a smaller k.
- This solution is the fundamental one, because, again, if there were a solution with smaller x it would have been found earlier.
` % Do...while
@:U % Push row vector [1^2, 2^2, ..., k^2] where k is the iteration index
t! % Duplicate and transpose. Gives the column vector [1^2; 2^2; ...; k^2]
G* % Multiply by input n, element-wise. Gives [n*1^2; n*2^2; ...; n*k^2]
- % Subtract with broadcast. Gives a square matrix of size n
! % Transpose, so that x corresponds to row index and y to column index
1=&f % Push row and column indices of all entries that equal 1. There can
% only be (a) zero such entries, in which case the results are , ,
% or (b) one such entry, in which case the results are the solution x, y
ts~ % Duplicate, sum, negate. This gives 1 in case (a) or 0 in case (b)
% End (implicit). Proceed with next iteration if top of the stack is true;
% that is, if no solution was found.
% Display (implicit). The stack contains copies of , and x, y on top.
% The empty array is not displayed
$endgroup$
add a comment |
$begingroup$
Haskell, 46 bytes
A straightforward brute force search. This makes use of the fact that a fundamental solution $(x,y)$ satisfying $x^2 - ny^2 = 1 $ must have $y leq x$.
f n=[(x,y)|x<-[1..],y<-[1..n],x^2-n*y^2==1]!!0
Try it online!
$endgroup$
add a comment |
$begingroup$
TI-BASIC, 44 42 41 bytes
Ans→N:"√(N⁻¹(X²-1→Y₁:1→X:Repeat not(fPart(Ans:X+1→X:Y₁:End:{X,Ans
Input is $n$.
Output is a list whose values correspond to $(x,y)$.
Uses the equation $y=sqrt{frac{x^2-1}{n}}$ for $xge2$ to calculate the fundamental solution.
The current $(x,y)$ pair for that equation is a fundamental solution iff $ybmod1=0$.
Examples:
6
6
prgmCDGF12
{5 2}
10
10
prgmCDGF12
{19 6}
13
13
prgmCDGF12
{649 180}
Explanation:
Ans→N:"√(N⁻¹(X²+1→Y₁:1→X:Repeat not(fPart(Ans:X+1→X:Y₁:End:{X,Ans ;full logic
Ans→N ;store the input in "N"
"√(N⁻¹(X²+1→Y₁ ;store the aforementioned
; equation into the first
; function variable
1→X ;store 1 in "X"
Repeat not(fPart(Ans End ;loop until "Ans" is
; an integer
X+1→X ;increment "X" by 1
Y₁ ;evaluate the function
; stored in this variable
; at "X" and leave the
; result in "Ans"
{X,Ans ;create a list whose
; values contain "X" and
; "Ans" and leave it in
; "Ans"
;implicitly print "Ans"
Note: TI-BASIC is a tokenized language. Character count does not equal byte count.
$endgroup$
add a comment |
$begingroup$
C# (Visual C# Interactive Compiler), 70 69 bytes
n=>{int x=1;var y=.1;for(;y%1>0;)y=Math.Sqrt(-x*~++x/n);return(x,y);}
Port of my Java 8 answer, but outputs a tuple instead of a string to save bytes.
Try it online.
$endgroup$
add a comment |
$begingroup$
Husk, 12 bytes
ḟΛ¤ȯ=→*⁰□π2N
Try it online!
Explanation
ḟΛ¤ȯ=→*⁰□π2N Input is n, accessed through ⁰.
N Natural numbers: [1,2,3,4,..
π2 2-tuples, ordered by sum: [[1,1],[1,2],[2,1],[1,3],[2,2],..
ḟ Find the first that satisfies this:
Λ All adjacent pairs x,y satisfy this:
¤ □ Square both: x²,y²
ȯ *⁰ Multiply second number by n: x²,ny²
→ Increment second number: x²,ny²+1
= These are equal.
$endgroup$
add a comment |
$begingroup$
Jelly, 40 bytes
½©%1İ$<®‘¤$п¹;Ḋ$LḂ$?Ḟṭ@ṫ-ṚZæ.ʋ¥ƒØ.,U¤-ị
Try it online!
An alternative Jelly answer, less golfy but more efficient algorithmically when x and y are large. This finds the convergents of the regular continued fraction that approximate the square root of n, and then checks which solve the Pell equation. Now correctly finds the period of the regular continued fraction.
Thanks to @TimPederick, I’ve also implemented an integer-based solution which should handle any number:
Jelly, 68 bytes
U×_ƭ/;²®_$÷2ị$}ʋ¥µ;+®Æ½W¤:/$$
¹©Æ½Ø.;ÇƬṪ€F¹;Ḋ$LḂ$?ṭ@ṫ-ṚZæ.ʋ¥ƒØ.,U¤-ị
Try it online!
For example, the solution for 1234567890 has 1936 and 1932 digits for the numerator and denominator respectively.
$endgroup$
$begingroup$
Nice! I took the same approach in my answer. I don't read Jelly, so I'm not sure why you're having problems with 61. Are you storing each convergent as a pair of integers (numerator and denominator)?
$endgroup$
– Tim Pederick
yesterday
$begingroup$
@TimPederick Yes. Not sure where the issue arises
$endgroup$
– Nick Kennedy
yesterday
$begingroup$
I tried learning how this works so I could help debug it, but I just couldn't wrap my head around it! Only thing I can suggest is taking the floor of any floats, since (if this does use the same algorithm as mine) all intermediate values should come out as integers anyway.
$endgroup$
– Tim Pederick
18 hours ago
$begingroup$
@TimPederick It was floating point inaccuracy. I’ve now made it stop looking for further continuation of the continued fraction once it reaches the period. This works up to 150, but above that I think again I run into floating point accuracy errors at e.g. 151
$endgroup$
– Nick Kennedy
12 hours ago
$begingroup$
@TimPederick also it’s the generation of the continued fraction that’s problematic, not the convergents which are done with integer arithmetic.
$endgroup$
– Nick Kennedy
12 hours ago
|
show 2 more comments
$begingroup$
Groovy, 53 bytes
n->x=1;for(y=0.1d;y%1>0;)y=((++x*x-1)/n)**0.5;x+" "+y
Try it online!
Port of Kevin Cruijssen's Java and C# answers
$endgroup$
add a comment |
$begingroup$
Jelly, 15 bytes
‘ɼ²×³‘½µ⁺%1$¿;®
Try it online!
A full program that takes a single argument n
and returns a tuple of x, y
.
$endgroup$
add a comment |
$begingroup$
Pyth, 15 bytes
fsIJ@ct*TTQ2 2J
Try it online here. Output is x
then y
separated by a newline.
$endgroup$
add a comment |
$begingroup$
Wolfram Language (Mathematica), 41 bytes
{1//.y_/;!NumberQ[x=√(y^2#+1)]:>y+1,x}&
√
is the 3-byte Unicode character #221A. Outputs the solution in the order (y,x) instead of (x,y). As usual with the imperfect //.
and its limited iterations, only works on inputs where the true value of y
is at most 65538.
Try it online!
$endgroup$
add a comment |
$begingroup$
><>, 45 bytes
11v
+$~:1
:}/!?:-1v?=1-*}:{*:@:{*:
$ naon;>
Try it online!
Brute force algorithm, searching from x=2
upwards, with y=x-1
and decrementing on each loop, incrementing x
when y
reaches 0. Output is x
followed by y
, separated by a newline.
$endgroup$
add a comment |
$begingroup$
C# (Visual C# Interactive Compiler), 69 bytes
n=>{for(int x=2,y;;x++)for(y=0;y<=x;y++)if(x*x-y*y*n==1)return(x,y);}
Try it online!
$endgroup$
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "200"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodegolf.stackexchange.com%2fquestions%2f183298%2ffundamental-solution-of-the-pell-equation%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
21 Answers
21
active
oldest
votes
21 Answers
21
active
oldest
votes
active
oldest
votes
active
oldest
votes
$begingroup$
Piet, 612 codels
Takes n from standard input. Outputs y then x, space-separated.
Codel size 1:
Codel size 4, for easier viewing:
Explanation
Check out this NPiet trace, which shows the program calculating the solution for an input value of 99.
I'm not sure whether I'd ever heard of Pell's equation before this challenge, so I got all of the following from Wikipedia; specifically, these sections of three articles:
- Pell's equation § Fundamental solution via continued fractions
- Methods of computing square roots § Continued fraction expansion
- Continued fraction § Infinite continued fractions and convergents
Basically, what we do is this:
- Get $n$ from standard input.
- Find $lfloorsqrt nrfloor$ by incrementing a counter until its square exceeds $n$, then decrement it once. (This is the first loop you can see in the trace, at top left.)
- Set up some variables for calculating $x$ and $y$ from the continued fraction of $sqrt n$.
- Check whether $x$ and $y$ fit Pell's equation yet. If they do, output the values (this is the downwards branch about 2/3 of the way across) and then exit (by running into the red block at far left).
- If not, iteratively update the variables and go back to step 4. (This is the wide loop out to the right, back across the bottom, and rejoining not quite halfway across.)
I frankly have no idea whether or not a brute-force approach would be shorter, and I'm not about to try it! Okay, so I tried it.
$endgroup$
add a comment |
$begingroup$
Piet, 612 codels
Takes n from standard input. Outputs y then x, space-separated.
Codel size 1:
Codel size 4, for easier viewing:
Explanation
Check out this NPiet trace, which shows the program calculating the solution for an input value of 99.
I'm not sure whether I'd ever heard of Pell's equation before this challenge, so I got all of the following from Wikipedia; specifically, these sections of three articles:
- Pell's equation § Fundamental solution via continued fractions
- Methods of computing square roots § Continued fraction expansion
- Continued fraction § Infinite continued fractions and convergents
Basically, what we do is this:
- Get $n$ from standard input.
- Find $lfloorsqrt nrfloor$ by incrementing a counter until its square exceeds $n$, then decrement it once. (This is the first loop you can see in the trace, at top left.)
- Set up some variables for calculating $x$ and $y$ from the continued fraction of $sqrt n$.
- Check whether $x$ and $y$ fit Pell's equation yet. If they do, output the values (this is the downwards branch about 2/3 of the way across) and then exit (by running into the red block at far left).
- If not, iteratively update the variables and go back to step 4. (This is the wide loop out to the right, back across the bottom, and rejoining not quite halfway across.)
I frankly have no idea whether or not a brute-force approach would be shorter, and I'm not about to try it! Okay, so I tried it.
$endgroup$
add a comment |
$begingroup$
Piet, 612 codels
Takes n from standard input. Outputs y then x, space-separated.
Codel size 1:
Codel size 4, for easier viewing:
Explanation
Check out this NPiet trace, which shows the program calculating the solution for an input value of 99.
I'm not sure whether I'd ever heard of Pell's equation before this challenge, so I got all of the following from Wikipedia; specifically, these sections of three articles:
- Pell's equation § Fundamental solution via continued fractions
- Methods of computing square roots § Continued fraction expansion
- Continued fraction § Infinite continued fractions and convergents
Basically, what we do is this:
- Get $n$ from standard input.
- Find $lfloorsqrt nrfloor$ by incrementing a counter until its square exceeds $n$, then decrement it once. (This is the first loop you can see in the trace, at top left.)
- Set up some variables for calculating $x$ and $y$ from the continued fraction of $sqrt n$.
- Check whether $x$ and $y$ fit Pell's equation yet. If they do, output the values (this is the downwards branch about 2/3 of the way across) and then exit (by running into the red block at far left).
- If not, iteratively update the variables and go back to step 4. (This is the wide loop out to the right, back across the bottom, and rejoining not quite halfway across.)
I frankly have no idea whether or not a brute-force approach would be shorter, and I'm not about to try it! Okay, so I tried it.
$endgroup$
Piet, 612 codels
Takes n from standard input. Outputs y then x, space-separated.
Codel size 1:
Codel size 4, for easier viewing:
Explanation
Check out this NPiet trace, which shows the program calculating the solution for an input value of 99.
I'm not sure whether I'd ever heard of Pell's equation before this challenge, so I got all of the following from Wikipedia; specifically, these sections of three articles:
- Pell's equation § Fundamental solution via continued fractions
- Methods of computing square roots § Continued fraction expansion
- Continued fraction § Infinite continued fractions and convergents
Basically, what we do is this:
- Get $n$ from standard input.
- Find $lfloorsqrt nrfloor$ by incrementing a counter until its square exceeds $n$, then decrement it once. (This is the first loop you can see in the trace, at top left.)
- Set up some variables for calculating $x$ and $y$ from the continued fraction of $sqrt n$.
- Check whether $x$ and $y$ fit Pell's equation yet. If they do, output the values (this is the downwards branch about 2/3 of the way across) and then exit (by running into the red block at far left).
- If not, iteratively update the variables and go back to step 4. (This is the wide loop out to the right, back across the bottom, and rejoining not quite halfway across.)
I frankly have no idea whether or not a brute-force approach would be shorter, and I'm not about to try it! Okay, so I tried it.
edited 18 hours ago
answered yesterday
Tim PederickTim Pederick
1,181710
1,181710
add a comment |
add a comment |
$begingroup$
Brachylog, 16 bytes
;1↔;Ċz×ᵐ-1∧Ċ√ᵐℕᵐ
Try it online!
Explanation
;1↔ Take the list [1, Input]
;Ċz Zip it with a couple of two unknown variables: [[1,I],[Input,J]]
×ᵐ Map multiply: [I, Input×J]
-1 I - Input×J must be equal to 1
∧ (and)
Ċ√ᵐ We are looking for the square roots of these two unknown variables
ℕᵐ And they must be natural numbers
(implicit attempt to find values that match those constraints)
$endgroup$
add a comment |
$begingroup$
Brachylog, 16 bytes
;1↔;Ċz×ᵐ-1∧Ċ√ᵐℕᵐ
Try it online!
Explanation
;1↔ Take the list [1, Input]
;Ċz Zip it with a couple of two unknown variables: [[1,I],[Input,J]]
×ᵐ Map multiply: [I, Input×J]
-1 I - Input×J must be equal to 1
∧ (and)
Ċ√ᵐ We are looking for the square roots of these two unknown variables
ℕᵐ And they must be natural numbers
(implicit attempt to find values that match those constraints)
$endgroup$
add a comment |
$begingroup$
Brachylog, 16 bytes
;1↔;Ċz×ᵐ-1∧Ċ√ᵐℕᵐ
Try it online!
Explanation
;1↔ Take the list [1, Input]
;Ċz Zip it with a couple of two unknown variables: [[1,I],[Input,J]]
×ᵐ Map multiply: [I, Input×J]
-1 I - Input×J must be equal to 1
∧ (and)
Ċ√ᵐ We are looking for the square roots of these two unknown variables
ℕᵐ And they must be natural numbers
(implicit attempt to find values that match those constraints)
$endgroup$
Brachylog, 16 bytes
;1↔;Ċz×ᵐ-1∧Ċ√ᵐℕᵐ
Try it online!
Explanation
;1↔ Take the list [1, Input]
;Ċz Zip it with a couple of two unknown variables: [[1,I],[Input,J]]
×ᵐ Map multiply: [I, Input×J]
-1 I - Input×J must be equal to 1
∧ (and)
Ċ√ᵐ We are looking for the square roots of these two unknown variables
ℕᵐ And they must be natural numbers
(implicit attempt to find values that match those constraints)
answered yesterday
FatalizeFatalize
28.1k449136
28.1k449136
add a comment |
add a comment |
$begingroup$
Pari/GP, 36 bytes
PARI/GP almost has a built-in for this: quadunit
gives the fundamental unit of the quadratic field $mathbb{Q}(sqrt{D})$, where $D$ is the discriminant of the field. In other words, quadunit(4*n)
solves the Pell's equation $x^2 - n cdot y^2 = pm 1$. So I have to take the square when its norm is $-1$.
I don't know what algorithm it uses, but it even works when $n$ is not square-free.
Answers are given in the form x + y*w
, where w
denotes $sqrt{n}$.
n->if(norm(a=quadunit(4*n))>0,a,a^2)
Try it online!
$endgroup$
add a comment |
$begingroup$
Pari/GP, 36 bytes
PARI/GP almost has a built-in for this: quadunit
gives the fundamental unit of the quadratic field $mathbb{Q}(sqrt{D})$, where $D$ is the discriminant of the field. In other words, quadunit(4*n)
solves the Pell's equation $x^2 - n cdot y^2 = pm 1$. So I have to take the square when its norm is $-1$.
I don't know what algorithm it uses, but it even works when $n$ is not square-free.
Answers are given in the form x + y*w
, where w
denotes $sqrt{n}$.
n->if(norm(a=quadunit(4*n))>0,a,a^2)
Try it online!
$endgroup$
add a comment |
$begingroup$
Pari/GP, 36 bytes
PARI/GP almost has a built-in for this: quadunit
gives the fundamental unit of the quadratic field $mathbb{Q}(sqrt{D})$, where $D$ is the discriminant of the field. In other words, quadunit(4*n)
solves the Pell's equation $x^2 - n cdot y^2 = pm 1$. So I have to take the square when its norm is $-1$.
I don't know what algorithm it uses, but it even works when $n$ is not square-free.
Answers are given in the form x + y*w
, where w
denotes $sqrt{n}$.
n->if(norm(a=quadunit(4*n))>0,a,a^2)
Try it online!
$endgroup$
Pari/GP, 36 bytes
PARI/GP almost has a built-in for this: quadunit
gives the fundamental unit of the quadratic field $mathbb{Q}(sqrt{D})$, where $D$ is the discriminant of the field. In other words, quadunit(4*n)
solves the Pell's equation $x^2 - n cdot y^2 = pm 1$. So I have to take the square when its norm is $-1$.
I don't know what algorithm it uses, but it even works when $n$ is not square-free.
Answers are given in the form x + y*w
, where w
denotes $sqrt{n}$.
n->if(norm(a=quadunit(4*n))>0,a,a^2)
Try it online!
edited yesterday
answered yesterday
alephalphaalephalpha
22.1k33095
22.1k33095
add a comment |
add a comment |
$begingroup$
Piet, 184 codels
This is the brute-force alternative I said (in my other answer) that I didn't want to write. It takes over 2 minutes to compute the solution for n = 13. I really don't want to try it on n = 29... but it checks out for every n up to 20, so I'm confident that it's correct.
Like that other answer, this takes n from standard input and outputs y then x, space-separated.
Codel size 1:
Codel size 4, for easier viewing:
Explanation
Here's the NPiet trace for an input value of 5.
This is the most brutal of brute force, iterating over both $x$ and $y$. Other solutions might iterate over $x$ and then calculate $y=sqrt{frac{x^2-1}{n}}$, but they're wimps.
Starting from $x=2$ and $y=1$, this checks whether $x$ and $y$ have solved the equation yet. If it has (the fork at the bottom near the right), it outputs the values and exits.
If not, it continues left, where $y$ is incremented and compared to $x$. (Then there's some direction-twiddling to follow the zig-zag path.)
This last comparison is where the path splits around the mid-left. If they're equal, $x$ is incremented and $y$ is set back to 1. And we go back to checking if it's a solution yet.
I still have some whitespace available, so maybe I'll see if I can incorporate that square-root calculation without enlarging the program.
$endgroup$
2
$begingroup$
Haha I agree about the wimps that use square roots :D
$endgroup$
– flawr
18 hours ago
add a comment |
$begingroup$
Piet, 184 codels
This is the brute-force alternative I said (in my other answer) that I didn't want to write. It takes over 2 minutes to compute the solution for n = 13. I really don't want to try it on n = 29... but it checks out for every n up to 20, so I'm confident that it's correct.
Like that other answer, this takes n from standard input and outputs y then x, space-separated.
Codel size 1:
Codel size 4, for easier viewing:
Explanation
Here's the NPiet trace for an input value of 5.
This is the most brutal of brute force, iterating over both $x$ and $y$. Other solutions might iterate over $x$ and then calculate $y=sqrt{frac{x^2-1}{n}}$, but they're wimps.
Starting from $x=2$ and $y=1$, this checks whether $x$ and $y$ have solved the equation yet. If it has (the fork at the bottom near the right), it outputs the values and exits.
If not, it continues left, where $y$ is incremented and compared to $x$. (Then there's some direction-twiddling to follow the zig-zag path.)
This last comparison is where the path splits around the mid-left. If they're equal, $x$ is incremented and $y$ is set back to 1. And we go back to checking if it's a solution yet.
I still have some whitespace available, so maybe I'll see if I can incorporate that square-root calculation without enlarging the program.
$endgroup$
2
$begingroup$
Haha I agree about the wimps that use square roots :D
$endgroup$
– flawr
18 hours ago
add a comment |
$begingroup$
Piet, 184 codels
This is the brute-force alternative I said (in my other answer) that I didn't want to write. It takes over 2 minutes to compute the solution for n = 13. I really don't want to try it on n = 29... but it checks out for every n up to 20, so I'm confident that it's correct.
Like that other answer, this takes n from standard input and outputs y then x, space-separated.
Codel size 1:
Codel size 4, for easier viewing:
Explanation
Here's the NPiet trace for an input value of 5.
This is the most brutal of brute force, iterating over both $x$ and $y$. Other solutions might iterate over $x$ and then calculate $y=sqrt{frac{x^2-1}{n}}$, but they're wimps.
Starting from $x=2$ and $y=1$, this checks whether $x$ and $y$ have solved the equation yet. If it has (the fork at the bottom near the right), it outputs the values and exits.
If not, it continues left, where $y$ is incremented and compared to $x$. (Then there's some direction-twiddling to follow the zig-zag path.)
This last comparison is where the path splits around the mid-left. If they're equal, $x$ is incremented and $y$ is set back to 1. And we go back to checking if it's a solution yet.
I still have some whitespace available, so maybe I'll see if I can incorporate that square-root calculation without enlarging the program.
$endgroup$
Piet, 184 codels
This is the brute-force alternative I said (in my other answer) that I didn't want to write. It takes over 2 minutes to compute the solution for n = 13. I really don't want to try it on n = 29... but it checks out for every n up to 20, so I'm confident that it's correct.
Like that other answer, this takes n from standard input and outputs y then x, space-separated.
Codel size 1:
Codel size 4, for easier viewing:
Explanation
Here's the NPiet trace for an input value of 5.
This is the most brutal of brute force, iterating over both $x$ and $y$. Other solutions might iterate over $x$ and then calculate $y=sqrt{frac{x^2-1}{n}}$, but they're wimps.
Starting from $x=2$ and $y=1$, this checks whether $x$ and $y$ have solved the equation yet. If it has (the fork at the bottom near the right), it outputs the values and exits.
If not, it continues left, where $y$ is incremented and compared to $x$. (Then there's some direction-twiddling to follow the zig-zag path.)
This last comparison is where the path splits around the mid-left. If they're equal, $x$ is incremented and $y$ is set back to 1. And we go back to checking if it's a solution yet.
I still have some whitespace available, so maybe I'll see if I can incorporate that square-root calculation without enlarging the program.
answered 18 hours ago
Tim PederickTim Pederick
1,181710
1,181710
2
$begingroup$
Haha I agree about the wimps that use square roots :D
$endgroup$
– flawr
18 hours ago
add a comment |
2
$begingroup$
Haha I agree about the wimps that use square roots :D
$endgroup$
– flawr
18 hours ago
2
2
$begingroup$
Haha I agree about the wimps that use square roots :D
$endgroup$
– flawr
18 hours ago
$begingroup$
Haha I agree about the wimps that use square roots :D
$endgroup$
– flawr
18 hours ago
add a comment |
$begingroup$
Wolfram Language (Mathematica), 46 bytes
FindInstance[x^2-y^2#==1&&x>1,{x,y},Integers]&
Try it online!
$endgroup$
1
$begingroup$
Is it assured that this always finds the fundamental solution?
$endgroup$
– Greg Martin
21 hours ago
$begingroup$
@GregMartin yes, it is.This always finds the first (minimum) solution. In this case this always returns {1,0}. That is why we have to choose x>1 and get the second (fundamental) solution
$endgroup$
– J42161217
16 hours ago
1
$begingroup$
I would like that to be true, but nothing in the documentation seems to indicate that....
$endgroup$
– Greg Martin
16 hours ago
$begingroup$
@GregMartin I have used this function many times and already knew how it worked. My only concern was to skip the first solution and that cost me those 5 extra bytes. You can easily write a program and test it (just to confirm millions of results)
$endgroup$
– J42161217
16 hours ago
add a comment |
$begingroup$
Wolfram Language (Mathematica), 46 bytes
FindInstance[x^2-y^2#==1&&x>1,{x,y},Integers]&
Try it online!
$endgroup$
1
$begingroup$
Is it assured that this always finds the fundamental solution?
$endgroup$
– Greg Martin
21 hours ago
$begingroup$
@GregMartin yes, it is.This always finds the first (minimum) solution. In this case this always returns {1,0}. That is why we have to choose x>1 and get the second (fundamental) solution
$endgroup$
– J42161217
16 hours ago
1
$begingroup$
I would like that to be true, but nothing in the documentation seems to indicate that....
$endgroup$
– Greg Martin
16 hours ago
$begingroup$
@GregMartin I have used this function many times and already knew how it worked. My only concern was to skip the first solution and that cost me those 5 extra bytes. You can easily write a program and test it (just to confirm millions of results)
$endgroup$
– J42161217
16 hours ago
add a comment |
$begingroup$
Wolfram Language (Mathematica), 46 bytes
FindInstance[x^2-y^2#==1&&x>1,{x,y},Integers]&
Try it online!
$endgroup$
Wolfram Language (Mathematica), 46 bytes
FindInstance[x^2-y^2#==1&&x>1,{x,y},Integers]&
Try it online!
answered yesterday
J42161217J42161217
14.2k21353
14.2k21353
1
$begingroup$
Is it assured that this always finds the fundamental solution?
$endgroup$
– Greg Martin
21 hours ago
$begingroup$
@GregMartin yes, it is.This always finds the first (minimum) solution. In this case this always returns {1,0}. That is why we have to choose x>1 and get the second (fundamental) solution
$endgroup$
– J42161217
16 hours ago
1
$begingroup$
I would like that to be true, but nothing in the documentation seems to indicate that....
$endgroup$
– Greg Martin
16 hours ago
$begingroup$
@GregMartin I have used this function many times and already knew how it worked. My only concern was to skip the first solution and that cost me those 5 extra bytes. You can easily write a program and test it (just to confirm millions of results)
$endgroup$
– J42161217
16 hours ago
add a comment |
1
$begingroup$
Is it assured that this always finds the fundamental solution?
$endgroup$
– Greg Martin
21 hours ago
$begingroup$
@GregMartin yes, it is.This always finds the first (minimum) solution. In this case this always returns {1,0}. That is why we have to choose x>1 and get the second (fundamental) solution
$endgroup$
– J42161217
16 hours ago
1
$begingroup$
I would like that to be true, but nothing in the documentation seems to indicate that....
$endgroup$
– Greg Martin
16 hours ago
$begingroup$
@GregMartin I have used this function many times and already knew how it worked. My only concern was to skip the first solution and that cost me those 5 extra bytes. You can easily write a program and test it (just to confirm millions of results)
$endgroup$
– J42161217
16 hours ago
1
1
$begingroup$
Is it assured that this always finds the fundamental solution?
$endgroup$
– Greg Martin
21 hours ago
$begingroup$
Is it assured that this always finds the fundamental solution?
$endgroup$
– Greg Martin
21 hours ago
$begingroup$
@GregMartin yes, it is.This always finds the first (minimum) solution. In this case this always returns {1,0}. That is why we have to choose x>1 and get the second (fundamental) solution
$endgroup$
– J42161217
16 hours ago
$begingroup$
@GregMartin yes, it is.This always finds the first (minimum) solution. In this case this always returns {1,0}. That is why we have to choose x>1 and get the second (fundamental) solution
$endgroup$
– J42161217
16 hours ago
1
1
$begingroup$
I would like that to be true, but nothing in the documentation seems to indicate that....
$endgroup$
– Greg Martin
16 hours ago
$begingroup$
I would like that to be true, but nothing in the documentation seems to indicate that....
$endgroup$
– Greg Martin
16 hours ago
$begingroup$
@GregMartin I have used this function many times and already knew how it worked. My only concern was to skip the first solution and that cost me those 5 extra bytes. You can easily write a program and test it (just to confirm millions of results)
$endgroup$
– J42161217
16 hours ago
$begingroup$
@GregMartin I have used this function many times and already knew how it worked. My only concern was to skip the first solution and that cost me those 5 extra bytes. You can easily write a program and test it (just to confirm millions of results)
$endgroup$
– J42161217
16 hours ago
add a comment |
$begingroup$
05AB1E, 17 16 14 bytes
Saved a byte thanks to Kevin Cruijssen.
Outputs [y, x]
∞.Δn*>t©1%_}®‚
Try it online!
Explanation
∞ # from the infinite list of numbers [1 ...]
.Δ } # find the first number that returns true under
n # square
* # multiply with input
> # increment
t© # sqrt (and save to register as potential x)
1% # modulus 1
_ # logical negation
®‚ # pair result (y) with register (x)
$endgroup$
$begingroup$
And you beat me to it again.. had a 17 byter as well, but it didn't work becauseŲ
is bugged with decimals.. >.< Anyway, you can remove both,
and add a trailing‚
(no, the comma's are not the same ;p) to save a byte.
$endgroup$
– Kevin Cruijssen
yesterday
$begingroup$
@KevinCruijssen: Thanks! Yeah I also went forŲ
first noticing that it didn't work as expected.
$endgroup$
– Emigna
yesterday
add a comment |
$begingroup$
05AB1E, 17 16 14 bytes
Saved a byte thanks to Kevin Cruijssen.
Outputs [y, x]
∞.Δn*>t©1%_}®‚
Try it online!
Explanation
∞ # from the infinite list of numbers [1 ...]
.Δ } # find the first number that returns true under
n # square
* # multiply with input
> # increment
t© # sqrt (and save to register as potential x)
1% # modulus 1
_ # logical negation
®‚ # pair result (y) with register (x)
$endgroup$
$begingroup$
And you beat me to it again.. had a 17 byter as well, but it didn't work becauseŲ
is bugged with decimals.. >.< Anyway, you can remove both,
and add a trailing‚
(no, the comma's are not the same ;p) to save a byte.
$endgroup$
– Kevin Cruijssen
yesterday
$begingroup$
@KevinCruijssen: Thanks! Yeah I also went forŲ
first noticing that it didn't work as expected.
$endgroup$
– Emigna
yesterday
add a comment |
$begingroup$
05AB1E, 17 16 14 bytes
Saved a byte thanks to Kevin Cruijssen.
Outputs [y, x]
∞.Δn*>t©1%_}®‚
Try it online!
Explanation
∞ # from the infinite list of numbers [1 ...]
.Δ } # find the first number that returns true under
n # square
* # multiply with input
> # increment
t© # sqrt (and save to register as potential x)
1% # modulus 1
_ # logical negation
®‚ # pair result (y) with register (x)
$endgroup$
05AB1E, 17 16 14 bytes
Saved a byte thanks to Kevin Cruijssen.
Outputs [y, x]
∞.Δn*>t©1%_}®‚
Try it online!
Explanation
∞ # from the infinite list of numbers [1 ...]
.Δ } # find the first number that returns true under
n # square
* # multiply with input
> # increment
t© # sqrt (and save to register as potential x)
1% # modulus 1
_ # logical negation
®‚ # pair result (y) with register (x)
edited yesterday
answered yesterday
EmignaEmigna
48.1k434146
48.1k434146
$begingroup$
And you beat me to it again.. had a 17 byter as well, but it didn't work becauseŲ
is bugged with decimals.. >.< Anyway, you can remove both,
and add a trailing‚
(no, the comma's are not the same ;p) to save a byte.
$endgroup$
– Kevin Cruijssen
yesterday
$begingroup$
@KevinCruijssen: Thanks! Yeah I also went forŲ
first noticing that it didn't work as expected.
$endgroup$
– Emigna
yesterday
add a comment |
$begingroup$
And you beat me to it again.. had a 17 byter as well, but it didn't work becauseŲ
is bugged with decimals.. >.< Anyway, you can remove both,
and add a trailing‚
(no, the comma's are not the same ;p) to save a byte.
$endgroup$
– Kevin Cruijssen
yesterday
$begingroup$
@KevinCruijssen: Thanks! Yeah I also went forŲ
first noticing that it didn't work as expected.
$endgroup$
– Emigna
yesterday
$begingroup$
And you beat me to it again.. had a 17 byter as well, but it didn't work because
Ų
is bugged with decimals.. >.< Anyway, you can remove both ,
and add a trailing ‚
(no, the comma's are not the same ;p) to save a byte.$endgroup$
– Kevin Cruijssen
yesterday
$begingroup$
And you beat me to it again.. had a 17 byter as well, but it didn't work because
Ų
is bugged with decimals.. >.< Anyway, you can remove both ,
and add a trailing ‚
(no, the comma's are not the same ;p) to save a byte.$endgroup$
– Kevin Cruijssen
yesterday
$begingroup$
@KevinCruijssen: Thanks! Yeah I also went for
Ų
first noticing that it didn't work as expected.$endgroup$
– Emigna
yesterday
$begingroup$
@KevinCruijssen: Thanks! Yeah I also went for
Ų
first noticing that it didn't work as expected.$endgroup$
– Emigna
yesterday
add a comment |
$begingroup$
Java 8, 74 73 72 bytes
n->{int x=1;var y=.1;for(;y%1>0;)y=Math.sqrt(-x*~++x/n);return x+" "+y;}
-1 byte thanks to @Arnauld.
-1 byte thanks to @OlivierGrégoire.
Try it online.
Explanation:
n->{ // Method with double parameter and string return-type
int x=1; // Integer `x`, starting at 1
var y=.1; // Double `y`, starting at 0.1
for(;y%1>0;) // Loop as long as `y` contains decimal digits:
y= // Set `y` to:
Math.sqrt( // The square-root of:
-x* // Negative `x`, multiplied by
~++x // `(-x-2)` (or `-(x+1)-1)` to be exact)
// (because we increase `x` by 1 first with `++x`)
/n); // Divided by the input
return x+" "+y;} // After the loop, return `x` and `y` with space-delimiter as result
$endgroup$
1
$begingroup$
72 bytes, by changingn
to adouble
, andx
to anint
, playing on the fact thatx*x-1
is equal to(-x-1)*(-x+1)
.
$endgroup$
– Olivier Grégoire
yesterday
$begingroup$
Well, I'm actually playing on the fact that(x+1)*(x+1)-1
is equal to-x*-(x+2)
, to be entirely correct.
$endgroup$
– Olivier Grégoire
yesterday
add a comment |
$begingroup$
Java 8, 74 73 72 bytes
n->{int x=1;var y=.1;for(;y%1>0;)y=Math.sqrt(-x*~++x/n);return x+" "+y;}
-1 byte thanks to @Arnauld.
-1 byte thanks to @OlivierGrégoire.
Try it online.
Explanation:
n->{ // Method with double parameter and string return-type
int x=1; // Integer `x`, starting at 1
var y=.1; // Double `y`, starting at 0.1
for(;y%1>0;) // Loop as long as `y` contains decimal digits:
y= // Set `y` to:
Math.sqrt( // The square-root of:
-x* // Negative `x`, multiplied by
~++x // `(-x-2)` (or `-(x+1)-1)` to be exact)
// (because we increase `x` by 1 first with `++x`)
/n); // Divided by the input
return x+" "+y;} // After the loop, return `x` and `y` with space-delimiter as result
$endgroup$
1
$begingroup$
72 bytes, by changingn
to adouble
, andx
to anint
, playing on the fact thatx*x-1
is equal to(-x-1)*(-x+1)
.
$endgroup$
– Olivier Grégoire
yesterday
$begingroup$
Well, I'm actually playing on the fact that(x+1)*(x+1)-1
is equal to-x*-(x+2)
, to be entirely correct.
$endgroup$
– Olivier Grégoire
yesterday
add a comment |
$begingroup$
Java 8, 74 73 72 bytes
n->{int x=1;var y=.1;for(;y%1>0;)y=Math.sqrt(-x*~++x/n);return x+" "+y;}
-1 byte thanks to @Arnauld.
-1 byte thanks to @OlivierGrégoire.
Try it online.
Explanation:
n->{ // Method with double parameter and string return-type
int x=1; // Integer `x`, starting at 1
var y=.1; // Double `y`, starting at 0.1
for(;y%1>0;) // Loop as long as `y` contains decimal digits:
y= // Set `y` to:
Math.sqrt( // The square-root of:
-x* // Negative `x`, multiplied by
~++x // `(-x-2)` (or `-(x+1)-1)` to be exact)
// (because we increase `x` by 1 first with `++x`)
/n); // Divided by the input
return x+" "+y;} // After the loop, return `x` and `y` with space-delimiter as result
$endgroup$
Java 8, 74 73 72 bytes
n->{int x=1;var y=.1;for(;y%1>0;)y=Math.sqrt(-x*~++x/n);return x+" "+y;}
-1 byte thanks to @Arnauld.
-1 byte thanks to @OlivierGrégoire.
Try it online.
Explanation:
n->{ // Method with double parameter and string return-type
int x=1; // Integer `x`, starting at 1
var y=.1; // Double `y`, starting at 0.1
for(;y%1>0;) // Loop as long as `y` contains decimal digits:
y= // Set `y` to:
Math.sqrt( // The square-root of:
-x* // Negative `x`, multiplied by
~++x // `(-x-2)` (or `-(x+1)-1)` to be exact)
// (because we increase `x` by 1 first with `++x`)
/n); // Divided by the input
return x+" "+y;} // After the loop, return `x` and `y` with space-delimiter as result
edited yesterday
answered yesterday
Kevin CruijssenKevin Cruijssen
43.1k571221
43.1k571221
1
$begingroup$
72 bytes, by changingn
to adouble
, andx
to anint
, playing on the fact thatx*x-1
is equal to(-x-1)*(-x+1)
.
$endgroup$
– Olivier Grégoire
yesterday
$begingroup$
Well, I'm actually playing on the fact that(x+1)*(x+1)-1
is equal to-x*-(x+2)
, to be entirely correct.
$endgroup$
– Olivier Grégoire
yesterday
add a comment |
1
$begingroup$
72 bytes, by changingn
to adouble
, andx
to anint
, playing on the fact thatx*x-1
is equal to(-x-1)*(-x+1)
.
$endgroup$
– Olivier Grégoire
yesterday
$begingroup$
Well, I'm actually playing on the fact that(x+1)*(x+1)-1
is equal to-x*-(x+2)
, to be entirely correct.
$endgroup$
– Olivier Grégoire
yesterday
1
1
$begingroup$
72 bytes, by changing
n
to a double
, and x
to an int
, playing on the fact that x*x-1
is equal to (-x-1)*(-x+1)
.$endgroup$
– Olivier Grégoire
yesterday
$begingroup$
72 bytes, by changing
n
to a double
, and x
to an int
, playing on the fact that x*x-1
is equal to (-x-1)*(-x+1)
.$endgroup$
– Olivier Grégoire
yesterday
$begingroup$
Well, I'm actually playing on the fact that
(x+1)*(x+1)-1
is equal to -x*-(x+2)
, to be entirely correct.$endgroup$
– Olivier Grégoire
yesterday
$begingroup$
Well, I'm actually playing on the fact that
(x+1)*(x+1)-1
is equal to -x*-(x+2)
, to be entirely correct.$endgroup$
– Olivier Grégoire
yesterday
add a comment |
$begingroup$
R, 66 56 54 53 52 47 45 bytes
a full program
n=scan();while((x=(1+n*T^2)^.5)%%1)T=T+1;x;+T
-1 -2 thanks to @Giuseppe
-7 thanks to @Giuseppe & @Robin Ryder
-2 @JAD
$endgroup$
1
$begingroup$
use.5
instead of0.5
$endgroup$
– Giuseppe
yesterday
4
$begingroup$
46 bytes. Finding the smallest value ofx
is equivalent to finding the smallest value ofy
. This allows you to save 2 bytes because expressingx
in terms ofy
is shorter than the other way around, and 4 bytes by using the trick of usingT
which is initialized at 1.
$endgroup$
– Robin Ryder
yesterday
1
$begingroup$
@RobinRyder you might need a+T
at the end to make sure that wheny==1
it returns1
instead ofTRUE
but I'm not entirely sure.
$endgroup$
– Giuseppe
yesterday
2
$begingroup$
@Giuseppe Well spotted! You are right. That makes it 47 bytes
$endgroup$
– Robin Ryder
yesterday
1
$begingroup$
Seems to fail on n=61 (the silly large test case) due to big number issues. I think it's fine to allow for language limits, just noting the exception.
$endgroup$
– CriminallyVulgar
14 hours ago
|
show 5 more comments
$begingroup$
R, 66 56 54 53 52 47 45 bytes
a full program
n=scan();while((x=(1+n*T^2)^.5)%%1)T=T+1;x;+T
-1 -2 thanks to @Giuseppe
-7 thanks to @Giuseppe & @Robin Ryder
-2 @JAD
$endgroup$
1
$begingroup$
use.5
instead of0.5
$endgroup$
– Giuseppe
yesterday
4
$begingroup$
46 bytes. Finding the smallest value ofx
is equivalent to finding the smallest value ofy
. This allows you to save 2 bytes because expressingx
in terms ofy
is shorter than the other way around, and 4 bytes by using the trick of usingT
which is initialized at 1.
$endgroup$
– Robin Ryder
yesterday
1
$begingroup$
@RobinRyder you might need a+T
at the end to make sure that wheny==1
it returns1
instead ofTRUE
but I'm not entirely sure.
$endgroup$
– Giuseppe
yesterday
2
$begingroup$
@Giuseppe Well spotted! You are right. That makes it 47 bytes
$endgroup$
– Robin Ryder
yesterday
1
$begingroup$
Seems to fail on n=61 (the silly large test case) due to big number issues. I think it's fine to allow for language limits, just noting the exception.
$endgroup$
– CriminallyVulgar
14 hours ago
|
show 5 more comments
$begingroup$
R, 66 56 54 53 52 47 45 bytes
a full program
n=scan();while((x=(1+n*T^2)^.5)%%1)T=T+1;x;+T
-1 -2 thanks to @Giuseppe
-7 thanks to @Giuseppe & @Robin Ryder
-2 @JAD
$endgroup$
R, 66 56 54 53 52 47 45 bytes
a full program
n=scan();while((x=(1+n*T^2)^.5)%%1)T=T+1;x;+T
-1 -2 thanks to @Giuseppe
-7 thanks to @Giuseppe & @Robin Ryder
-2 @JAD
edited 14 hours ago
answered yesterday
Zahiro MorZahiro Mor
30128
30128
1
$begingroup$
use.5
instead of0.5
$endgroup$
– Giuseppe
yesterday
4
$begingroup$
46 bytes. Finding the smallest value ofx
is equivalent to finding the smallest value ofy
. This allows you to save 2 bytes because expressingx
in terms ofy
is shorter than the other way around, and 4 bytes by using the trick of usingT
which is initialized at 1.
$endgroup$
– Robin Ryder
yesterday
1
$begingroup$
@RobinRyder you might need a+T
at the end to make sure that wheny==1
it returns1
instead ofTRUE
but I'm not entirely sure.
$endgroup$
– Giuseppe
yesterday
2
$begingroup$
@Giuseppe Well spotted! You are right. That makes it 47 bytes
$endgroup$
– Robin Ryder
yesterday
1
$begingroup$
Seems to fail on n=61 (the silly large test case) due to big number issues. I think it's fine to allow for language limits, just noting the exception.
$endgroup$
– CriminallyVulgar
14 hours ago
|
show 5 more comments
1
$begingroup$
use.5
instead of0.5
$endgroup$
– Giuseppe
yesterday
4
$begingroup$
46 bytes. Finding the smallest value ofx
is equivalent to finding the smallest value ofy
. This allows you to save 2 bytes because expressingx
in terms ofy
is shorter than the other way around, and 4 bytes by using the trick of usingT
which is initialized at 1.
$endgroup$
– Robin Ryder
yesterday
1
$begingroup$
@RobinRyder you might need a+T
at the end to make sure that wheny==1
it returns1
instead ofTRUE
but I'm not entirely sure.
$endgroup$
– Giuseppe
yesterday
2
$begingroup$
@Giuseppe Well spotted! You are right. That makes it 47 bytes
$endgroup$
– Robin Ryder
yesterday
1
$begingroup$
Seems to fail on n=61 (the silly large test case) due to big number issues. I think it's fine to allow for language limits, just noting the exception.
$endgroup$
– CriminallyVulgar
14 hours ago
1
1
$begingroup$
use
.5
instead of 0.5
$endgroup$
– Giuseppe
yesterday
$begingroup$
use
.5
instead of 0.5
$endgroup$
– Giuseppe
yesterday
4
4
$begingroup$
46 bytes. Finding the smallest value of
x
is equivalent to finding the smallest value of y
. This allows you to save 2 bytes because expressing x
in terms of y
is shorter than the other way around, and 4 bytes by using the trick of using T
which is initialized at 1.$endgroup$
– Robin Ryder
yesterday
$begingroup$
46 bytes. Finding the smallest value of
x
is equivalent to finding the smallest value of y
. This allows you to save 2 bytes because expressing x
in terms of y
is shorter than the other way around, and 4 bytes by using the trick of using T
which is initialized at 1.$endgroup$
– Robin Ryder
yesterday
1
1
$begingroup$
@RobinRyder you might need a
+T
at the end to make sure that when y==1
it returns 1
instead of TRUE
but I'm not entirely sure.$endgroup$
– Giuseppe
yesterday
$begingroup$
@RobinRyder you might need a
+T
at the end to make sure that when y==1
it returns 1
instead of TRUE
but I'm not entirely sure.$endgroup$
– Giuseppe
yesterday
2
2
$begingroup$
@Giuseppe Well spotted! You are right. That makes it 47 bytes
$endgroup$
– Robin Ryder
yesterday
$begingroup$
@Giuseppe Well spotted! You are right. That makes it 47 bytes
$endgroup$
– Robin Ryder
yesterday
1
1
$begingroup$
Seems to fail on n=61 (the silly large test case) due to big number issues. I think it's fine to allow for language limits, just noting the exception.
$endgroup$
– CriminallyVulgar
14 hours ago
$begingroup$
Seems to fail on n=61 (the silly large test case) due to big number issues. I think it's fine to allow for language limits, just noting the exception.
$endgroup$
– CriminallyVulgar
14 hours ago
|
show 5 more comments
$begingroup$
JavaScript (ES7), 47 bytes
n=>(g=x=>(y=((x*x-1)/n)**.5)%1?g(x+1):[x,y])(2)
Try it online!
Below is an alternate 49-byte version which keeps track of $x²-1$ directly instead of squaring $x$ at each iteration:
n=>[(g=x=>(y=(x/n)**.5)%1?1+g(x+=k+=2):2)(k=3),y]
Try it online!
Or we can go the non-recursive way for 50 bytes:
n=>eval('for(x=1;(y=((++x*x-1)/n)**.5)%1;);[x,y]')
Try it online!
$endgroup$
add a comment |
$begingroup$
JavaScript (ES7), 47 bytes
n=>(g=x=>(y=((x*x-1)/n)**.5)%1?g(x+1):[x,y])(2)
Try it online!
Below is an alternate 49-byte version which keeps track of $x²-1$ directly instead of squaring $x$ at each iteration:
n=>[(g=x=>(y=(x/n)**.5)%1?1+g(x+=k+=2):2)(k=3),y]
Try it online!
Or we can go the non-recursive way for 50 bytes:
n=>eval('for(x=1;(y=((++x*x-1)/n)**.5)%1;);[x,y]')
Try it online!
$endgroup$
add a comment |
$begingroup$
JavaScript (ES7), 47 bytes
n=>(g=x=>(y=((x*x-1)/n)**.5)%1?g(x+1):[x,y])(2)
Try it online!
Below is an alternate 49-byte version which keeps track of $x²-1$ directly instead of squaring $x$ at each iteration:
n=>[(g=x=>(y=(x/n)**.5)%1?1+g(x+=k+=2):2)(k=3),y]
Try it online!
Or we can go the non-recursive way for 50 bytes:
n=>eval('for(x=1;(y=((++x*x-1)/n)**.5)%1;);[x,y]')
Try it online!
$endgroup$
JavaScript (ES7), 47 bytes
n=>(g=x=>(y=((x*x-1)/n)**.5)%1?g(x+1):[x,y])(2)
Try it online!
Below is an alternate 49-byte version which keeps track of $x²-1$ directly instead of squaring $x$ at each iteration:
n=>[(g=x=>(y=(x/n)**.5)%1?1+g(x+=k+=2):2)(k=3),y]
Try it online!
Or we can go the non-recursive way for 50 bytes:
n=>eval('for(x=1;(y=((++x*x-1)/n)**.5)%1;);[x,y]')
Try it online!
edited yesterday
answered yesterday
ArnauldArnauld
81.5k797336
81.5k797336
add a comment |
add a comment |
$begingroup$
MATL, 17 bytes
`@:Ut!G*-!1=&fts~
Try it online!
Explanation
The code keeps increasing a counter k = 1, 2, 3, ... For each k, solutions x, y with 1 ≤ x ≤ k, 1 ≤ y ≤ k are searched. The process when some solution if found.
This procedure is guaranteed to find only one solution, which is precisely the fundamental one. To see why, note that
- Any solution x>0, y>0 for n>1 satisfies x>y.
- If x,y is a solution and x',y' is a different solution then necessarily x≠x' and y≠y'.
As a consequence of 1 and 2,
- When the procedure stops at a given k, only one solution exists for that k, because if there were two solutions one of them would been found earlier, and the process would have stopped with a smaller k.
- This solution is the fundamental one, because, again, if there were a solution with smaller x it would have been found earlier.
` % Do...while
@:U % Push row vector [1^2, 2^2, ..., k^2] where k is the iteration index
t! % Duplicate and transpose. Gives the column vector [1^2; 2^2; ...; k^2]
G* % Multiply by input n, element-wise. Gives [n*1^2; n*2^2; ...; n*k^2]
- % Subtract with broadcast. Gives a square matrix of size n
! % Transpose, so that x corresponds to row index and y to column index
1=&f % Push row and column indices of all entries that equal 1. There can
% only be (a) zero such entries, in which case the results are , ,
% or (b) one such entry, in which case the results are the solution x, y
ts~ % Duplicate, sum, negate. This gives 1 in case (a) or 0 in case (b)
% End (implicit). Proceed with next iteration if top of the stack is true;
% that is, if no solution was found.
% Display (implicit). The stack contains copies of , and x, y on top.
% The empty array is not displayed
$endgroup$
add a comment |
$begingroup$
MATL, 17 bytes
`@:Ut!G*-!1=&fts~
Try it online!
Explanation
The code keeps increasing a counter k = 1, 2, 3, ... For each k, solutions x, y with 1 ≤ x ≤ k, 1 ≤ y ≤ k are searched. The process when some solution if found.
This procedure is guaranteed to find only one solution, which is precisely the fundamental one. To see why, note that
- Any solution x>0, y>0 for n>1 satisfies x>y.
- If x,y is a solution and x',y' is a different solution then necessarily x≠x' and y≠y'.
As a consequence of 1 and 2,
- When the procedure stops at a given k, only one solution exists for that k, because if there were two solutions one of them would been found earlier, and the process would have stopped with a smaller k.
- This solution is the fundamental one, because, again, if there were a solution with smaller x it would have been found earlier.
` % Do...while
@:U % Push row vector [1^2, 2^2, ..., k^2] where k is the iteration index
t! % Duplicate and transpose. Gives the column vector [1^2; 2^2; ...; k^2]
G* % Multiply by input n, element-wise. Gives [n*1^2; n*2^2; ...; n*k^2]
- % Subtract with broadcast. Gives a square matrix of size n
! % Transpose, so that x corresponds to row index and y to column index
1=&f % Push row and column indices of all entries that equal 1. There can
% only be (a) zero such entries, in which case the results are , ,
% or (b) one such entry, in which case the results are the solution x, y
ts~ % Duplicate, sum, negate. This gives 1 in case (a) or 0 in case (b)
% End (implicit). Proceed with next iteration if top of the stack is true;
% that is, if no solution was found.
% Display (implicit). The stack contains copies of , and x, y on top.
% The empty array is not displayed
$endgroup$
add a comment |
$begingroup$
MATL, 17 bytes
`@:Ut!G*-!1=&fts~
Try it online!
Explanation
The code keeps increasing a counter k = 1, 2, 3, ... For each k, solutions x, y with 1 ≤ x ≤ k, 1 ≤ y ≤ k are searched. The process when some solution if found.
This procedure is guaranteed to find only one solution, which is precisely the fundamental one. To see why, note that
- Any solution x>0, y>0 for n>1 satisfies x>y.
- If x,y is a solution and x',y' is a different solution then necessarily x≠x' and y≠y'.
As a consequence of 1 and 2,
- When the procedure stops at a given k, only one solution exists for that k, because if there were two solutions one of them would been found earlier, and the process would have stopped with a smaller k.
- This solution is the fundamental one, because, again, if there were a solution with smaller x it would have been found earlier.
` % Do...while
@:U % Push row vector [1^2, 2^2, ..., k^2] where k is the iteration index
t! % Duplicate and transpose. Gives the column vector [1^2; 2^2; ...; k^2]
G* % Multiply by input n, element-wise. Gives [n*1^2; n*2^2; ...; n*k^2]
- % Subtract with broadcast. Gives a square matrix of size n
! % Transpose, so that x corresponds to row index and y to column index
1=&f % Push row and column indices of all entries that equal 1. There can
% only be (a) zero such entries, in which case the results are , ,
% or (b) one such entry, in which case the results are the solution x, y
ts~ % Duplicate, sum, negate. This gives 1 in case (a) or 0 in case (b)
% End (implicit). Proceed with next iteration if top of the stack is true;
% that is, if no solution was found.
% Display (implicit). The stack contains copies of , and x, y on top.
% The empty array is not displayed
$endgroup$
MATL, 17 bytes
`@:Ut!G*-!1=&fts~
Try it online!
Explanation
The code keeps increasing a counter k = 1, 2, 3, ... For each k, solutions x, y with 1 ≤ x ≤ k, 1 ≤ y ≤ k are searched. The process when some solution if found.
This procedure is guaranteed to find only one solution, which is precisely the fundamental one. To see why, note that
- Any solution x>0, y>0 for n>1 satisfies x>y.
- If x,y is a solution and x',y' is a different solution then necessarily x≠x' and y≠y'.
As a consequence of 1 and 2,
- When the procedure stops at a given k, only one solution exists for that k, because if there were two solutions one of them would been found earlier, and the process would have stopped with a smaller k.
- This solution is the fundamental one, because, again, if there were a solution with smaller x it would have been found earlier.
` % Do...while
@:U % Push row vector [1^2, 2^2, ..., k^2] where k is the iteration index
t! % Duplicate and transpose. Gives the column vector [1^2; 2^2; ...; k^2]
G* % Multiply by input n, element-wise. Gives [n*1^2; n*2^2; ...; n*k^2]
- % Subtract with broadcast. Gives a square matrix of size n
! % Transpose, so that x corresponds to row index and y to column index
1=&f % Push row and column indices of all entries that equal 1. There can
% only be (a) zero such entries, in which case the results are , ,
% or (b) one such entry, in which case the results are the solution x, y
ts~ % Duplicate, sum, negate. This gives 1 in case (a) or 0 in case (b)
% End (implicit). Proceed with next iteration if top of the stack is true;
% that is, if no solution was found.
% Display (implicit). The stack contains copies of , and x, y on top.
% The empty array is not displayed
edited 10 hours ago
answered 14 hours ago
Luis MendoLuis Mendo
75.4k889292
75.4k889292
add a comment |
add a comment |
$begingroup$
Haskell, 46 bytes
A straightforward brute force search. This makes use of the fact that a fundamental solution $(x,y)$ satisfying $x^2 - ny^2 = 1 $ must have $y leq x$.
f n=[(x,y)|x<-[1..],y<-[1..n],x^2-n*y^2==1]!!0
Try it online!
$endgroup$
add a comment |
$begingroup$
Haskell, 46 bytes
A straightforward brute force search. This makes use of the fact that a fundamental solution $(x,y)$ satisfying $x^2 - ny^2 = 1 $ must have $y leq x$.
f n=[(x,y)|x<-[1..],y<-[1..n],x^2-n*y^2==1]!!0
Try it online!
$endgroup$
add a comment |
$begingroup$
Haskell, 46 bytes
A straightforward brute force search. This makes use of the fact that a fundamental solution $(x,y)$ satisfying $x^2 - ny^2 = 1 $ must have $y leq x$.
f n=[(x,y)|x<-[1..],y<-[1..n],x^2-n*y^2==1]!!0
Try it online!
$endgroup$
Haskell, 46 bytes
A straightforward brute force search. This makes use of the fact that a fundamental solution $(x,y)$ satisfying $x^2 - ny^2 = 1 $ must have $y leq x$.
f n=[(x,y)|x<-[1..],y<-[1..n],x^2-n*y^2==1]!!0
Try it online!
answered yesterday
flawrflawr
27.3k667192
27.3k667192
add a comment |
add a comment |
$begingroup$
TI-BASIC, 44 42 41 bytes
Ans→N:"√(N⁻¹(X²-1→Y₁:1→X:Repeat not(fPart(Ans:X+1→X:Y₁:End:{X,Ans
Input is $n$.
Output is a list whose values correspond to $(x,y)$.
Uses the equation $y=sqrt{frac{x^2-1}{n}}$ for $xge2$ to calculate the fundamental solution.
The current $(x,y)$ pair for that equation is a fundamental solution iff $ybmod1=0$.
Examples:
6
6
prgmCDGF12
{5 2}
10
10
prgmCDGF12
{19 6}
13
13
prgmCDGF12
{649 180}
Explanation:
Ans→N:"√(N⁻¹(X²+1→Y₁:1→X:Repeat not(fPart(Ans:X+1→X:Y₁:End:{X,Ans ;full logic
Ans→N ;store the input in "N"
"√(N⁻¹(X²+1→Y₁ ;store the aforementioned
; equation into the first
; function variable
1→X ;store 1 in "X"
Repeat not(fPart(Ans End ;loop until "Ans" is
; an integer
X+1→X ;increment "X" by 1
Y₁ ;evaluate the function
; stored in this variable
; at "X" and leave the
; result in "Ans"
{X,Ans ;create a list whose
; values contain "X" and
; "Ans" and leave it in
; "Ans"
;implicitly print "Ans"
Note: TI-BASIC is a tokenized language. Character count does not equal byte count.
$endgroup$
add a comment |
$begingroup$
TI-BASIC, 44 42 41 bytes
Ans→N:"√(N⁻¹(X²-1→Y₁:1→X:Repeat not(fPart(Ans:X+1→X:Y₁:End:{X,Ans
Input is $n$.
Output is a list whose values correspond to $(x,y)$.
Uses the equation $y=sqrt{frac{x^2-1}{n}}$ for $xge2$ to calculate the fundamental solution.
The current $(x,y)$ pair for that equation is a fundamental solution iff $ybmod1=0$.
Examples:
6
6
prgmCDGF12
{5 2}
10
10
prgmCDGF12
{19 6}
13
13
prgmCDGF12
{649 180}
Explanation:
Ans→N:"√(N⁻¹(X²+1→Y₁:1→X:Repeat not(fPart(Ans:X+1→X:Y₁:End:{X,Ans ;full logic
Ans→N ;store the input in "N"
"√(N⁻¹(X²+1→Y₁ ;store the aforementioned
; equation into the first
; function variable
1→X ;store 1 in "X"
Repeat not(fPart(Ans End ;loop until "Ans" is
; an integer
X+1→X ;increment "X" by 1
Y₁ ;evaluate the function
; stored in this variable
; at "X" and leave the
; result in "Ans"
{X,Ans ;create a list whose
; values contain "X" and
; "Ans" and leave it in
; "Ans"
;implicitly print "Ans"
Note: TI-BASIC is a tokenized language. Character count does not equal byte count.
$endgroup$
add a comment |
$begingroup$
TI-BASIC, 44 42 41 bytes
Ans→N:"√(N⁻¹(X²-1→Y₁:1→X:Repeat not(fPart(Ans:X+1→X:Y₁:End:{X,Ans
Input is $n$.
Output is a list whose values correspond to $(x,y)$.
Uses the equation $y=sqrt{frac{x^2-1}{n}}$ for $xge2$ to calculate the fundamental solution.
The current $(x,y)$ pair for that equation is a fundamental solution iff $ybmod1=0$.
Examples:
6
6
prgmCDGF12
{5 2}
10
10
prgmCDGF12
{19 6}
13
13
prgmCDGF12
{649 180}
Explanation:
Ans→N:"√(N⁻¹(X²+1→Y₁:1→X:Repeat not(fPart(Ans:X+1→X:Y₁:End:{X,Ans ;full logic
Ans→N ;store the input in "N"
"√(N⁻¹(X²+1→Y₁ ;store the aforementioned
; equation into the first
; function variable
1→X ;store 1 in "X"
Repeat not(fPart(Ans End ;loop until "Ans" is
; an integer
X+1→X ;increment "X" by 1
Y₁ ;evaluate the function
; stored in this variable
; at "X" and leave the
; result in "Ans"
{X,Ans ;create a list whose
; values contain "X" and
; "Ans" and leave it in
; "Ans"
;implicitly print "Ans"
Note: TI-BASIC is a tokenized language. Character count does not equal byte count.
$endgroup$
TI-BASIC, 44 42 41 bytes
Ans→N:"√(N⁻¹(X²-1→Y₁:1→X:Repeat not(fPart(Ans:X+1→X:Y₁:End:{X,Ans
Input is $n$.
Output is a list whose values correspond to $(x,y)$.
Uses the equation $y=sqrt{frac{x^2-1}{n}}$ for $xge2$ to calculate the fundamental solution.
The current $(x,y)$ pair for that equation is a fundamental solution iff $ybmod1=0$.
Examples:
6
6
prgmCDGF12
{5 2}
10
10
prgmCDGF12
{19 6}
13
13
prgmCDGF12
{649 180}
Explanation:
Ans→N:"√(N⁻¹(X²+1→Y₁:1→X:Repeat not(fPart(Ans:X+1→X:Y₁:End:{X,Ans ;full logic
Ans→N ;store the input in "N"
"√(N⁻¹(X²+1→Y₁ ;store the aforementioned
; equation into the first
; function variable
1→X ;store 1 in "X"
Repeat not(fPart(Ans End ;loop until "Ans" is
; an integer
X+1→X ;increment "X" by 1
Y₁ ;evaluate the function
; stored in this variable
; at "X" and leave the
; result in "Ans"
{X,Ans ;create a list whose
; values contain "X" and
; "Ans" and leave it in
; "Ans"
;implicitly print "Ans"
Note: TI-BASIC is a tokenized language. Character count does not equal byte count.
edited yesterday
answered yesterday
TauTau
1,083519
1,083519
add a comment |
add a comment |
$begingroup$
C# (Visual C# Interactive Compiler), 70 69 bytes
n=>{int x=1;var y=.1;for(;y%1>0;)y=Math.Sqrt(-x*~++x/n);return(x,y);}
Port of my Java 8 answer, but outputs a tuple instead of a string to save bytes.
Try it online.
$endgroup$
add a comment |
$begingroup$
C# (Visual C# Interactive Compiler), 70 69 bytes
n=>{int x=1;var y=.1;for(;y%1>0;)y=Math.Sqrt(-x*~++x/n);return(x,y);}
Port of my Java 8 answer, but outputs a tuple instead of a string to save bytes.
Try it online.
$endgroup$
add a comment |
$begingroup$
C# (Visual C# Interactive Compiler), 70 69 bytes
n=>{int x=1;var y=.1;for(;y%1>0;)y=Math.Sqrt(-x*~++x/n);return(x,y);}
Port of my Java 8 answer, but outputs a tuple instead of a string to save bytes.
Try it online.
$endgroup$
C# (Visual C# Interactive Compiler), 70 69 bytes
n=>{int x=1;var y=.1;for(;y%1>0;)y=Math.Sqrt(-x*~++x/n);return(x,y);}
Port of my Java 8 answer, but outputs a tuple instead of a string to save bytes.
Try it online.
edited yesterday
answered yesterday
Kevin CruijssenKevin Cruijssen
43.1k571221
43.1k571221
add a comment |
add a comment |
$begingroup$
Husk, 12 bytes
ḟΛ¤ȯ=→*⁰□π2N
Try it online!
Explanation
ḟΛ¤ȯ=→*⁰□π2N Input is n, accessed through ⁰.
N Natural numbers: [1,2,3,4,..
π2 2-tuples, ordered by sum: [[1,1],[1,2],[2,1],[1,3],[2,2],..
ḟ Find the first that satisfies this:
Λ All adjacent pairs x,y satisfy this:
¤ □ Square both: x²,y²
ȯ *⁰ Multiply second number by n: x²,ny²
→ Increment second number: x²,ny²+1
= These are equal.
$endgroup$
add a comment |
$begingroup$
Husk, 12 bytes
ḟΛ¤ȯ=→*⁰□π2N
Try it online!
Explanation
ḟΛ¤ȯ=→*⁰□π2N Input is n, accessed through ⁰.
N Natural numbers: [1,2,3,4,..
π2 2-tuples, ordered by sum: [[1,1],[1,2],[2,1],[1,3],[2,2],..
ḟ Find the first that satisfies this:
Λ All adjacent pairs x,y satisfy this:
¤ □ Square both: x²,y²
ȯ *⁰ Multiply second number by n: x²,ny²
→ Increment second number: x²,ny²+1
= These are equal.
$endgroup$
add a comment |
$begingroup$
Husk, 12 bytes
ḟΛ¤ȯ=→*⁰□π2N
Try it online!
Explanation
ḟΛ¤ȯ=→*⁰□π2N Input is n, accessed through ⁰.
N Natural numbers: [1,2,3,4,..
π2 2-tuples, ordered by sum: [[1,1],[1,2],[2,1],[1,3],[2,2],..
ḟ Find the first that satisfies this:
Λ All adjacent pairs x,y satisfy this:
¤ □ Square both: x²,y²
ȯ *⁰ Multiply second number by n: x²,ny²
→ Increment second number: x²,ny²+1
= These are equal.
$endgroup$
Husk, 12 bytes
ḟΛ¤ȯ=→*⁰□π2N
Try it online!
Explanation
ḟΛ¤ȯ=→*⁰□π2N Input is n, accessed through ⁰.
N Natural numbers: [1,2,3,4,..
π2 2-tuples, ordered by sum: [[1,1],[1,2],[2,1],[1,3],[2,2],..
ḟ Find the first that satisfies this:
Λ All adjacent pairs x,y satisfy this:
¤ □ Square both: x²,y²
ȯ *⁰ Multiply second number by n: x²,ny²
→ Increment second number: x²,ny²+1
= These are equal.
edited 17 hours ago
answered 19 hours ago
ZgarbZgarb
26.8k462231
26.8k462231
add a comment |
add a comment |
$begingroup$
Jelly, 40 bytes
½©%1İ$<®‘¤$п¹;Ḋ$LḂ$?Ḟṭ@ṫ-ṚZæ.ʋ¥ƒØ.,U¤-ị
Try it online!
An alternative Jelly answer, less golfy but more efficient algorithmically when x and y are large. This finds the convergents of the regular continued fraction that approximate the square root of n, and then checks which solve the Pell equation. Now correctly finds the period of the regular continued fraction.
Thanks to @TimPederick, I’ve also implemented an integer-based solution which should handle any number:
Jelly, 68 bytes
U×_ƭ/;²®_$÷2ị$}ʋ¥µ;+®Æ½W¤:/$$
¹©Æ½Ø.;ÇƬṪ€F¹;Ḋ$LḂ$?ṭ@ṫ-ṚZæ.ʋ¥ƒØ.,U¤-ị
Try it online!
For example, the solution for 1234567890 has 1936 and 1932 digits for the numerator and denominator respectively.
$endgroup$
$begingroup$
Nice! I took the same approach in my answer. I don't read Jelly, so I'm not sure why you're having problems with 61. Are you storing each convergent as a pair of integers (numerator and denominator)?
$endgroup$
– Tim Pederick
yesterday
$begingroup$
@TimPederick Yes. Not sure where the issue arises
$endgroup$
– Nick Kennedy
yesterday
$begingroup$
I tried learning how this works so I could help debug it, but I just couldn't wrap my head around it! Only thing I can suggest is taking the floor of any floats, since (if this does use the same algorithm as mine) all intermediate values should come out as integers anyway.
$endgroup$
– Tim Pederick
18 hours ago
$begingroup$
@TimPederick It was floating point inaccuracy. I’ve now made it stop looking for further continuation of the continued fraction once it reaches the period. This works up to 150, but above that I think again I run into floating point accuracy errors at e.g. 151
$endgroup$
– Nick Kennedy
12 hours ago
$begingroup$
@TimPederick also it’s the generation of the continued fraction that’s problematic, not the convergents which are done with integer arithmetic.
$endgroup$
– Nick Kennedy
12 hours ago
|
show 2 more comments
$begingroup$
Jelly, 40 bytes
½©%1İ$<®‘¤$п¹;Ḋ$LḂ$?Ḟṭ@ṫ-ṚZæ.ʋ¥ƒØ.,U¤-ị
Try it online!
An alternative Jelly answer, less golfy but more efficient algorithmically when x and y are large. This finds the convergents of the regular continued fraction that approximate the square root of n, and then checks which solve the Pell equation. Now correctly finds the period of the regular continued fraction.
Thanks to @TimPederick, I’ve also implemented an integer-based solution which should handle any number:
Jelly, 68 bytes
U×_ƭ/;²®_$÷2ị$}ʋ¥µ;+®Æ½W¤:/$$
¹©Æ½Ø.;ÇƬṪ€F¹;Ḋ$LḂ$?ṭ@ṫ-ṚZæ.ʋ¥ƒØ.,U¤-ị
Try it online!
For example, the solution for 1234567890 has 1936 and 1932 digits for the numerator and denominator respectively.
$endgroup$
$begingroup$
Nice! I took the same approach in my answer. I don't read Jelly, so I'm not sure why you're having problems with 61. Are you storing each convergent as a pair of integers (numerator and denominator)?
$endgroup$
– Tim Pederick
yesterday
$begingroup$
@TimPederick Yes. Not sure where the issue arises
$endgroup$
– Nick Kennedy
yesterday
$begingroup$
I tried learning how this works so I could help debug it, but I just couldn't wrap my head around it! Only thing I can suggest is taking the floor of any floats, since (if this does use the same algorithm as mine) all intermediate values should come out as integers anyway.
$endgroup$
– Tim Pederick
18 hours ago
$begingroup$
@TimPederick It was floating point inaccuracy. I’ve now made it stop looking for further continuation of the continued fraction once it reaches the period. This works up to 150, but above that I think again I run into floating point accuracy errors at e.g. 151
$endgroup$
– Nick Kennedy
12 hours ago
$begingroup$
@TimPederick also it’s the generation of the continued fraction that’s problematic, not the convergents which are done with integer arithmetic.
$endgroup$
– Nick Kennedy
12 hours ago
|
show 2 more comments
$begingroup$
Jelly, 40 bytes
½©%1İ$<®‘¤$п¹;Ḋ$LḂ$?Ḟṭ@ṫ-ṚZæ.ʋ¥ƒØ.,U¤-ị
Try it online!
An alternative Jelly answer, less golfy but more efficient algorithmically when x and y are large. This finds the convergents of the regular continued fraction that approximate the square root of n, and then checks which solve the Pell equation. Now correctly finds the period of the regular continued fraction.
Thanks to @TimPederick, I’ve also implemented an integer-based solution which should handle any number:
Jelly, 68 bytes
U×_ƭ/;²®_$÷2ị$}ʋ¥µ;+®Æ½W¤:/$$
¹©Æ½Ø.;ÇƬṪ€F¹;Ḋ$LḂ$?ṭ@ṫ-ṚZæ.ʋ¥ƒØ.,U¤-ị
Try it online!
For example, the solution for 1234567890 has 1936 and 1932 digits for the numerator and denominator respectively.
$endgroup$
Jelly, 40 bytes
½©%1İ$<®‘¤$п¹;Ḋ$LḂ$?Ḟṭ@ṫ-ṚZæ.ʋ¥ƒØ.,U¤-ị
Try it online!
An alternative Jelly answer, less golfy but more efficient algorithmically when x and y are large. This finds the convergents of the regular continued fraction that approximate the square root of n, and then checks which solve the Pell equation. Now correctly finds the period of the regular continued fraction.
Thanks to @TimPederick, I’ve also implemented an integer-based solution which should handle any number:
Jelly, 68 bytes
U×_ƭ/;²®_$÷2ị$}ʋ¥µ;+®Æ½W¤:/$$
¹©Æ½Ø.;ÇƬṪ€F¹;Ḋ$LḂ$?ṭ@ṫ-ṚZæ.ʋ¥ƒØ.,U¤-ị
Try it online!
For example, the solution for 1234567890 has 1936 and 1932 digits for the numerator and denominator respectively.
edited 6 hours ago
answered yesterday
Nick KennedyNick Kennedy
1,72649
1,72649
$begingroup$
Nice! I took the same approach in my answer. I don't read Jelly, so I'm not sure why you're having problems with 61. Are you storing each convergent as a pair of integers (numerator and denominator)?
$endgroup$
– Tim Pederick
yesterday
$begingroup$
@TimPederick Yes. Not sure where the issue arises
$endgroup$
– Nick Kennedy
yesterday
$begingroup$
I tried learning how this works so I could help debug it, but I just couldn't wrap my head around it! Only thing I can suggest is taking the floor of any floats, since (if this does use the same algorithm as mine) all intermediate values should come out as integers anyway.
$endgroup$
– Tim Pederick
18 hours ago
$begingroup$
@TimPederick It was floating point inaccuracy. I’ve now made it stop looking for further continuation of the continued fraction once it reaches the period. This works up to 150, but above that I think again I run into floating point accuracy errors at e.g. 151
$endgroup$
– Nick Kennedy
12 hours ago
$begingroup$
@TimPederick also it’s the generation of the continued fraction that’s problematic, not the convergents which are done with integer arithmetic.
$endgroup$
– Nick Kennedy
12 hours ago
|
show 2 more comments
$begingroup$
Nice! I took the same approach in my answer. I don't read Jelly, so I'm not sure why you're having problems with 61. Are you storing each convergent as a pair of integers (numerator and denominator)?
$endgroup$
– Tim Pederick
yesterday
$begingroup$
@TimPederick Yes. Not sure where the issue arises
$endgroup$
– Nick Kennedy
yesterday
$begingroup$
I tried learning how this works so I could help debug it, but I just couldn't wrap my head around it! Only thing I can suggest is taking the floor of any floats, since (if this does use the same algorithm as mine) all intermediate values should come out as integers anyway.
$endgroup$
– Tim Pederick
18 hours ago
$begingroup$
@TimPederick It was floating point inaccuracy. I’ve now made it stop looking for further continuation of the continued fraction once it reaches the period. This works up to 150, but above that I think again I run into floating point accuracy errors at e.g. 151
$endgroup$
– Nick Kennedy
12 hours ago
$begingroup$
@TimPederick also it’s the generation of the continued fraction that’s problematic, not the convergents which are done with integer arithmetic.
$endgroup$
– Nick Kennedy
12 hours ago
$begingroup$
Nice! I took the same approach in my answer. I don't read Jelly, so I'm not sure why you're having problems with 61. Are you storing each convergent as a pair of integers (numerator and denominator)?
$endgroup$
– Tim Pederick
yesterday
$begingroup$
Nice! I took the same approach in my answer. I don't read Jelly, so I'm not sure why you're having problems with 61. Are you storing each convergent as a pair of integers (numerator and denominator)?
$endgroup$
– Tim Pederick
yesterday
$begingroup$
@TimPederick Yes. Not sure where the issue arises
$endgroup$
– Nick Kennedy
yesterday
$begingroup$
@TimPederick Yes. Not sure where the issue arises
$endgroup$
– Nick Kennedy
yesterday
$begingroup$
I tried learning how this works so I could help debug it, but I just couldn't wrap my head around it! Only thing I can suggest is taking the floor of any floats, since (if this does use the same algorithm as mine) all intermediate values should come out as integers anyway.
$endgroup$
– Tim Pederick
18 hours ago
$begingroup$
I tried learning how this works so I could help debug it, but I just couldn't wrap my head around it! Only thing I can suggest is taking the floor of any floats, since (if this does use the same algorithm as mine) all intermediate values should come out as integers anyway.
$endgroup$
– Tim Pederick
18 hours ago
$begingroup$
@TimPederick It was floating point inaccuracy. I’ve now made it stop looking for further continuation of the continued fraction once it reaches the period. This works up to 150, but above that I think again I run into floating point accuracy errors at e.g. 151
$endgroup$
– Nick Kennedy
12 hours ago
$begingroup$
@TimPederick It was floating point inaccuracy. I’ve now made it stop looking for further continuation of the continued fraction once it reaches the period. This works up to 150, but above that I think again I run into floating point accuracy errors at e.g. 151
$endgroup$
– Nick Kennedy
12 hours ago
$begingroup$
@TimPederick also it’s the generation of the continued fraction that’s problematic, not the convergents which are done with integer arithmetic.
$endgroup$
– Nick Kennedy
12 hours ago
$begingroup$
@TimPederick also it’s the generation of the continued fraction that’s problematic, not the convergents which are done with integer arithmetic.
$endgroup$
– Nick Kennedy
12 hours ago
|
show 2 more comments
$begingroup$
Groovy, 53 bytes
n->x=1;for(y=0.1d;y%1>0;)y=((++x*x-1)/n)**0.5;x+" "+y
Try it online!
Port of Kevin Cruijssen's Java and C# answers
$endgroup$
add a comment |
$begingroup$
Groovy, 53 bytes
n->x=1;for(y=0.1d;y%1>0;)y=((++x*x-1)/n)**0.5;x+" "+y
Try it online!
Port of Kevin Cruijssen's Java and C# answers
$endgroup$
add a comment |
$begingroup$
Groovy, 53 bytes
n->x=1;for(y=0.1d;y%1>0;)y=((++x*x-1)/n)**0.5;x+" "+y
Try it online!
Port of Kevin Cruijssen's Java and C# answers
$endgroup$
Groovy, 53 bytes
n->x=1;for(y=0.1d;y%1>0;)y=((++x*x-1)/n)**0.5;x+" "+y
Try it online!
Port of Kevin Cruijssen's Java and C# answers
answered yesterday
Expired DataExpired Data
1,018217
1,018217
add a comment |
add a comment |
$begingroup$
Jelly, 15 bytes
‘ɼ²×³‘½µ⁺%1$¿;®
Try it online!
A full program that takes a single argument n
and returns a tuple of x, y
.
$endgroup$
add a comment |
$begingroup$
Jelly, 15 bytes
‘ɼ²×³‘½µ⁺%1$¿;®
Try it online!
A full program that takes a single argument n
and returns a tuple of x, y
.
$endgroup$
add a comment |
$begingroup$
Jelly, 15 bytes
‘ɼ²×³‘½µ⁺%1$¿;®
Try it online!
A full program that takes a single argument n
and returns a tuple of x, y
.
$endgroup$
Jelly, 15 bytes
‘ɼ²×³‘½µ⁺%1$¿;®
Try it online!
A full program that takes a single argument n
and returns a tuple of x, y
.
answered yesterday
Nick KennedyNick Kennedy
1,72649
1,72649
add a comment |
add a comment |
$begingroup$
Pyth, 15 bytes
fsIJ@ct*TTQ2 2J
Try it online here. Output is x
then y
separated by a newline.
$endgroup$
add a comment |
$begingroup$
Pyth, 15 bytes
fsIJ@ct*TTQ2 2J
Try it online here. Output is x
then y
separated by a newline.
$endgroup$
add a comment |
$begingroup$
Pyth, 15 bytes
fsIJ@ct*TTQ2 2J
Try it online here. Output is x
then y
separated by a newline.
$endgroup$
Pyth, 15 bytes
fsIJ@ct*TTQ2 2J
Try it online here. Output is x
then y
separated by a newline.
answered yesterday
SokSok
4,237925
4,237925
add a comment |
add a comment |
$begingroup$
Wolfram Language (Mathematica), 41 bytes
{1//.y_/;!NumberQ[x=√(y^2#+1)]:>y+1,x}&
√
is the 3-byte Unicode character #221A. Outputs the solution in the order (y,x) instead of (x,y). As usual with the imperfect //.
and its limited iterations, only works on inputs where the true value of y
is at most 65538.
Try it online!
$endgroup$
add a comment |
$begingroup$
Wolfram Language (Mathematica), 41 bytes
{1//.y_/;!NumberQ[x=√(y^2#+1)]:>y+1,x}&
√
is the 3-byte Unicode character #221A. Outputs the solution in the order (y,x) instead of (x,y). As usual with the imperfect //.
and its limited iterations, only works on inputs where the true value of y
is at most 65538.
Try it online!
$endgroup$
add a comment |
$begingroup$
Wolfram Language (Mathematica), 41 bytes
{1//.y_/;!NumberQ[x=√(y^2#+1)]:>y+1,x}&
√
is the 3-byte Unicode character #221A. Outputs the solution in the order (y,x) instead of (x,y). As usual with the imperfect //.
and its limited iterations, only works on inputs where the true value of y
is at most 65538.
Try it online!
$endgroup$
Wolfram Language (Mathematica), 41 bytes
{1//.y_/;!NumberQ[x=√(y^2#+1)]:>y+1,x}&
√
is the 3-byte Unicode character #221A. Outputs the solution in the order (y,x) instead of (x,y). As usual with the imperfect //.
and its limited iterations, only works on inputs where the true value of y
is at most 65538.
Try it online!
answered 21 hours ago
Greg MartinGreg Martin
12.4k21059
12.4k21059
add a comment |
add a comment |
$begingroup$
><>, 45 bytes
11v
+$~:1
:}/!?:-1v?=1-*}:{*:@:{*:
$ naon;>
Try it online!
Brute force algorithm, searching from x=2
upwards, with y=x-1
and decrementing on each loop, incrementing x
when y
reaches 0. Output is x
followed by y
, separated by a newline.
$endgroup$
add a comment |
$begingroup$
><>, 45 bytes
11v
+$~:1
:}/!?:-1v?=1-*}:{*:@:{*:
$ naon;>
Try it online!
Brute force algorithm, searching from x=2
upwards, with y=x-1
and decrementing on each loop, incrementing x
when y
reaches 0. Output is x
followed by y
, separated by a newline.
$endgroup$
add a comment |
$begingroup$
><>, 45 bytes
11v
+$~:1
:}/!?:-1v?=1-*}:{*:@:{*:
$ naon;>
Try it online!
Brute force algorithm, searching from x=2
upwards, with y=x-1
and decrementing on each loop, incrementing x
when y
reaches 0. Output is x
followed by y
, separated by a newline.
$endgroup$
><>, 45 bytes
11v
+$~:1
:}/!?:-1v?=1-*}:{*:@:{*:
$ naon;>
Try it online!
Brute force algorithm, searching from x=2
upwards, with y=x-1
and decrementing on each loop, incrementing x
when y
reaches 0. Output is x
followed by y
, separated by a newline.
answered 17 hours ago
SokSok
4,237925
4,237925
add a comment |
add a comment |
$begingroup$
C# (Visual C# Interactive Compiler), 69 bytes
n=>{for(int x=2,y;;x++)for(y=0;y<=x;y++)if(x*x-y*y*n==1)return(x,y);}
Try it online!
$endgroup$
add a comment |
$begingroup$
C# (Visual C# Interactive Compiler), 69 bytes
n=>{for(int x=2,y;;x++)for(y=0;y<=x;y++)if(x*x-y*y*n==1)return(x,y);}
Try it online!
$endgroup$
add a comment |
$begingroup$
C# (Visual C# Interactive Compiler), 69 bytes
n=>{for(int x=2,y;;x++)for(y=0;y<=x;y++)if(x*x-y*y*n==1)return(x,y);}
Try it online!
$endgroup$
C# (Visual C# Interactive Compiler), 69 bytes
n=>{for(int x=2,y;;x++)for(y=0;y<=x;y++)if(x*x-y*y*n==1)return(x,y);}
Try it online!
answered 4 hours ago
Embodiment of IgnoranceEmbodiment of Ignorance
2,994127
2,994127
add a comment |
add a comment |
If this is an answer to a challenge…
…Be sure to follow the challenge specification. However, please refrain from exploiting obvious loopholes. Answers abusing any of the standard loopholes are considered invalid. If you think a specification is unclear or underspecified, comment on the question instead.
…Try to optimize your score. For instance, answers to code-golf challenges should attempt to be as short as possible. You can always include a readable version of the code in addition to the competitive one.
Explanations of your answer make it more interesting to read and are very much encouraged.…Include a short header which indicates the language(s) of your code and its score, as defined by the challenge.
More generally…
…Please make sure to answer the question and provide sufficient detail.
…Avoid asking for help, clarification or responding to other answers (use comments instead).
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodegolf.stackexchange.com%2fquestions%2f183298%2ffundamental-solution-of-the-pell-equation%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
$begingroup$
Surprised that there isn't any challenge with the Pell equation yet, since it's pretty well-known I thought. At least, I do remember using it sometimes with Project Euler challenges.
$endgroup$
– Kevin Cruijssen
yesterday
$begingroup$
@Fatalize "You can assume that $n$ is not a square." Would probably be clearer if the test cases omitted those imho, though.
$endgroup$
– Kevin Cruijssen
yesterday
1
$begingroup$
@KevinCruijssen I considered that, but I thought it would be more confusing to omit some of the
n
s. (btw I was also surprized but I had this challenge in the sandbox for about a year)$endgroup$
– flawr
yesterday