开发者

Why do I not get the correct answer for Euler 56 in J?

I've solved 84 of the Project Euler problems, mostly in Haskell. I am now going back and trying to solve in J some of those I already solved in Haskell, as an exercise in learning J.

Currently, I am trying to solve Problem 56. Let me stress that I already know what the right answer is, since I've already solved it in Haskell. It's a very easy, trivial problem. I will not give the answer here.

Here is my solution in J:

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

This produces a number less than the desired result. In other words, it's wrong somehow. Any J-ers out there know why? I'm baffled, since it's pretty straightforward and totally brute force.


The reason is that you are applying extended precision (x:) too late in the game. Switch to extended precision the very first thing you do (e.g. i. x: 99) and your should be all set.

One other note, regarding your cartesian. You might want to have a look at J's 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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜