Why am I not getting the correct answer for Euler 56 in J?

I solved 84 Project Euler problems, mainly in Haskell. Now I come back and try to solve in J some of those that I have already decided in Haskell, as an exercise in learning J.

I am currently trying to solve Problem 56 . Let me emphasize that I already know that the correct answer , since I already solved it in Haskell. This is a very simple, trivial problem. I will not answer here.

Here is my solution in J:

digits =: ("." 0) @ ":" 0
eachDigit =: adverb: ' u @ : digits "0' NB. I use this so often I made it an adverb.
cartesian =: adverb: '((# # ~ #) u ($ ~ *: @ #))'
> ./ + / eachDigit x: ^ cartesian>: i. 99

This leads to the fact that the number is less than the desired result. In other words, this is wrong. Does anyone know why? I am puzzled, as it is a fairly simple and complete brute force.

+3
source share
1 answer

The reason is that you use extended precision ( x:) too late in the game. Switch to advanced precision, the first thing you do (like i. x: 99), and everything should be set.

One more note regarding yours cartesian. Perhaps you should take a look at the J built-in "table" adverb ( /) :

   ^/~ >: i.5
1  1   1   1    1
2  4   8  16   32
3  9  27  81  243
4 16  64 256 1024
5 25 125 625 3125

   , ^/~ >: i.3
1 1 1 2 4 8 3 9 27
+3
source

Source: https://habr.com/ru/post/1750065/


All Articles