Tuesday, September 29, 2009

Bignum in GNU CLISP

Today I read the document  http://www.ai.mit.edu/projects/iiip/doc/CommonLISP/HyperSpec/Body/typ...  , find that there is a type named bignum. But I can not find any more information about it. After posting on the Comp.Lang.Lisp, I got some information from Tamas and Pascal
Bignums: you may restrict integers to a certain range, making them fixnums.  Integers which are not fixnums are bignums. 
Actually , we do not need worry about it. The CL implement will choose the right representation for us.
CL-USER> (type-of (1+ most-positive-fixnum)) 
(INTEGER 536870912) 
CL-USER> (typep (1+ most-positive-fixnum) 'bignum) 

Bignum in GNU CLISP

Today I read the document  http://www.ai.mit.edu/projects/iiip/doc/CommonLISP/HyperSpec/Body/typ...  , find that there is a type named bignum. But I can not find any more information about it. After posting on the Comp.Lang.Lisp, I got some information from Tamas and Pascal
Bignums: you may restrict integers to a certain range, making them fixnums.  Integers which are not fixnums are bignums. 
Actually , we do not need worry about it. The CL implement will choose the right representation for us.
CL-USER> (type-of (1+ most-positive-fixnum)) 
(INTEGER 536870912) 
CL-USER> (typep (1+ most-positive-fixnum) 'bignum) 

Sunday, September 27, 2009

Convert Number to Digits

In Mathematica, there is a useful function which is used to convert number to digits IntegerDigits. I think we also can use the CL to do it.

One Solution


(defun digits (n &optional (base 10)) 

   (do ((digits '())) ((zerop n) digits) 

     (multiple-value-bind (quotient remainder) (truncate n base) 

       (push remainder digits) 

       (setf n quotient)))) 



Two Solution


(map 'list #'digit-char-p (prin1-to-string 15754548)) 


Or


(map 'list #'digit-char-p (format nil "~D" 15754548)


BTW:Thanks the help from Comp.Lang.Lisp

Thursday, September 24, 2009

Everyday Word 2009-09-24

initiate vt.开始, 着手传授; 使初步了解接纳新成员, 让…加入



cradle n.摇篮发源地, 发祥地吊架, 支架, 吊篮婴儿时期vt.将…置于摇篮中

ritualistic adj. 仪式的

garb n. (尤指某类人穿的特定)服装, 衣服; 制服


medieval adj.中古的, 中世纪的


heretic n.持异端者


gallows n.绞刑架


lambskin n. 小羊皮,羊皮纸


apron n.围裙


sash n.(作为衣服一部分的)腰带,(穿礼服时通常作为某种荣誉标志佩戴的)肩带


Saturday, September 19, 2009

Euler Project 44


Pentagonal numbers are generated by the formula, Pn=n(3n−1)/2. The first ten pentagonal numbers are:



1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ...



It can be seen that P4 + P7 = 22 + 70 = 92 = P8. However, their difference, 70 − 22 = 48, is not pentagonal.



Find the pair of pentagonal numbers, Pj and Pk, for which their sum and difference is pentagonal and D = |Pk − Pj| is minimised; what is the value of D?







My Solution Using Mathematica


For[i = 1, i < 5000, i++, 


 For[j = i + 1, j < 5001, j++, 


  If[MemberQ[MyTList, MyTList[[i]] + MyTList[[j]]] && 


    MemberQ[MyTList, 


     MyTList[[j]] - MyTList[[i]]] && (MyTList[[j]] - MyTList[[i]]) < 


     DNum , DNum = MyTList[[j]] - MyTList[[i]]]]]


Everyday word 2009-09-19

ablution n.洗浴,净礼
abnegate v.否认 放弃
abate v.减少 减轻
abdicate v.退位 辞职 放弃
aberrant adj.越轨的,异常的
abeyance n.中止 搁置
abhorrent adj. 可恨的 讨厌的
abominate v.痛恨 厌恶
abolition n.废除 革除
aboveboard adj. 正大光明的

Euler Project 43


The number, 1406357289, is a 0 to 9 pandigital number because it is made up of each of the digits 0 to 9 in some order, but it also has a rather interesting sub-string divisibility property.



Let d1 be the 1st digit, d2 be the 2nd digit, and so on. In this way, we note the following:




  • d2d3d4=406 is divisible by 2


  • d3d4d5=063 is divisible by 3


  • d4d5d6=635 is divisible by 5


  • d5d6d7=357 is divisible by 7


  • d6d7d8=572 is divisible by 11


  • d7d8d9=728 is divisible by 13


  • d8d9d10=289 is divisible by 17



Find the sum of all 0 to 9 pandigital numbers with this property.








My Solution Using Mathematica



For[i = 362880, i < 3628801, i++, TempList = NthPermutation[i, MyList];



 For[j = 2, j < 9, j++, 


  If[! Divisible[FromDigits[TempList[[j ;; (j + 2)]]], 


     DivisorList[[j - 1]]], Flag = False; Break[]]];If[Flag, TotalSum = TotalSum + FromDigits[TempList]; Flag = True;]


Euler Project 42


The nth term of the sequence of triangle numbers is given by, tn = ½n(n+1); so the first ten triangle numbers are:



1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...



By converting each letter in a word to a number corresponding to its alphabetical position and adding these values we form a word value. For example, the word value for SKY is 19 + 11 + 25 = 55 = t10. If the word value is a triangle number then we shall call the word a triangle word.



Using words.txt (right click and 'Save Link/Target As...'), a 16K text file containing nearly two-thousand common English words, how many are triangle words?








My Solution Using Mathematica



TripleNumList = Table[i*(i + 1)/2, {i, 200}];





For[i = 1, i < NumberOfWords + 1, i++, 


 If[MemberQ[TripleNumList, 


   Total[Map[# - 64 &, ToCharacterCode[fs[[i]]]]]], NumberT++]]




Euler Project 22


Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score.



For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 × 53 = 49714.



What is the total of all the name scores in the file?








My Solution Using Mathematica





For[i = 1, i < NumberOfWords + 1, i++, 


 TotalNum = TotalNum + i*Total[Map[# - 64 &, ToCharacterCode[fs[[i]]]]]]

Friday, September 18, 2009

Euler Project 99


Comparing two numbers written in index form like 211 and 37 is not difficult, as any calculator would confirm that 211 = 2048 < 37 = 2187.



However, confirming that 632382518061 > 519432525806 would be much more difficult, as both numbers contain over three million digits.



Using base_exp.txt (right click and 'Save Link/Target As...'), a 22K text file containing one thousand lines with a base/exponent pair on each line, determine which line number has the greatest numerical value.



NOTE: The first two lines in the file represent the numbers in the example given above.








My Solution Using Mathematic



MaxIndex = 0;MaxNum=0;





For[i = 1, i < 2000, i = i + 2, 


 TempValue = N[Log[10, ToExpression[fs[[i]]]], 20]*ToExpression[fs[[i + 1]]]; 


                 If[TempValue > MaxNum, MaxNum = TempValue; MaxIndex = i]]




Everyday word 2009-09-18

annotate vt. & vi.注解, 注释
parasol n. (女用)阳伞
eery adj. 怪诞的,奇异的,不安的,可怕的
dart n.飞镖急驰, 飞奔vi.向前冲; 飞奔 vt.投掷; 投射
arbiter n.权威人士
arable adj. 可耕种的
arcane adj.神秘的
argot n.隐语,黑话
ardent adj.热心的,热烈的
arena n.(角斗的)竞技场

Euler Project 79

A common security method used for online banking is to ask the user for three random characters from a passcode. For example, if the passcode was 531278, they may asked for the 2nd, 3rd, and 5th characters; the expected reply would be: 317.
The text file, keylog.txt, contains fifty successful login attempts.
Given that the three characters are always asked for in order, analyse the file so as to determine the shortest possible secret passcode of unknown length.
I do it by pencil and paper.

Thursday, September 17, 2009

Everyday word 2009-09-17

asterisk n. 星号
asteroid n. 小行星
asthma n. 哮喘病
astute adj. 机敏的 精明的
asylum n.避难所
atrocious adj. 凶恶的
awe n/v 敬畏
avow v. 承认 公开宣称
averse adj. 不愿的 反对的
asperity n.严酷 粗鲁

Euler Project 50

The prime 41, can be written as the sum of six consecutive primes:


41 = 2 + 3 + 5 + 7 + 11 + 13


This is the longest sum of consecutive primes that adds to a prime below one-hundred.
The longest sum of consecutive primes below one-thousand that adds to a prime, contains 21 terms, and is equal to 953.
Which prime, below one-million, can be written as the sum of the most consecutive primes?

My Solution Using Mathematica

MyPrimesList = Table[Prime[i], {i, PrimePi[1000000]}]
MostLength = 0; CurrentPrimes = 2; TempValue = 0; TempCount = 0;
For[i = 1, i < 10000, i++, TempValue = 0; TempCount = 0; 
For[j = i, j < 10000, j++, TempCount = TempCount + 1; 
TempValue = TempValue + MyPrimesList[[j]]; 
 If[TempValue > 1000000, Break[]]; 
 If[PrimeQ[TempValue], If[TempCount > MostLength, MostLength = TempCount; CurrentPrimes = i]]]





Others' Solution




First Solution


(defun sieve (lst)
(let ((primes '())
(last (car (last lst))))
(loop while (and lst (> last (* (car lst) (car lst))))
do (let ((factor (car lst)))
(setq primes (cons factor primes))
(setq lst (remove-if
#'(lambda (n)
(= (mod n factor) 0))
(cdr lst)))))
(append (reverse primes) lst)))

(defun seq-list (min max)
(loop for i from min to max collect i))

(defun all-primes (limit)
(sieve (seq-list 2 limit)))

(defun generate-all-primes (limit)
(setq all-primes (all-primes limit))
(setq primehash (make-hash-table))
(loop for p in all-primes
do (setf (gethash p primehash) p)))

(defun primep (p)
(gethash p primehash))

(defun generate-prime-sums (limit)
(setq primesumhash (make-hash-table))
(generate-all-primes limit)
(loop for allp on all-primes
do (loop for p in allp
sum p into pp
while (< pp limit)
append (list p) into pl
if (and (primep pp)
(> (length pl)
(length (gethash pp primesumhash '()))))
do (setf (gethash pp primesumhash) (copy-list pl)))))

(defun euler50 ()
(generate-prime-sums 1000000)
(let ((psums (loop for p being each hash-key of primesumhash
append (list (cons p (gethash p primesumhash))))))
(sort psums #'(lambda (a b) (< (length a) (length b))))
(car (last psums)))) 




Second Solution
p = Prime /@ Range @ 78498;
partialsums = Rest@FoldList
[Plus, 0, p];
  

total[a_, b_] :=
     p[[a]] + ( partialsums[[b]] - partialsums[[a]])
  

inrange[a_, b_] := 
    total[a, b] < 1000000
  

hunt[width_] := Module[{a, b, n}
    {a, b} = {1, width}
     n = Length@ partialsums ; 
    While[b < n && inrange[a, b]
        If[PrimeQ@total[a, b], Return[{a, b}]]
        {a, b} += {1, 1}
        ]
    Return@{}
]
  



total@@Last@Select[hunt/@Range[1, 1000], Length@# > 0&]


Third Solution



Fourth Solution
(defun longest-cons-primesum (prime-list below)
(do* ((data prime-list (rest data))
(zwischen (loop for i in data
summing i into summe
while (< summe below)
counting i into lang
if (member summe data)
collecting (list lang summe))
(loop for i in data
summing i into summe
while (< summe below)
counting i into lang
if (member summe data)
collecting (list lang summe)))
(result zwischen (if (> (caar (last zwischen))
(caar (last result)))
zwischen
result)))
((> (reduce #'+ (subseq data 0 (caar (last result)))) below)
(last result))))

With this function you just have to generate the data and call it.

(defvar primes-below-million
(loop for i from 1 to 1000000 if (primep i) collecting i))

This takes around 12 seconds.

(longest-cons-primesum primes-below-million 1000000) 



Fifth Solution
(defun length-prime-sum-sequence (n0 max) 
    (let ((sum 0) 
          (seq-length 0)) 
        (iter (for i from n0 below (length *primes*)) 
               (for p = (aref *primes* i)) 
               (for s first p then (+ s p)) 
               (if (>= s max) 
                  (finish)) 
               (when (primep s) 
                    (setq sum s) 
                    (setq seq-length (- i n0))) 
               (finally (return (values (1+ seq-length) sum)))))))
  



(defun longest-sum-sequence (max) 
    (iter (for i from 0 below max) 
          (for (values length sum) = (length-prime-sum-sequence i max)) 
          (finding (list length sum) maximizing length)))

Wednesday, September 16, 2009

Euler Project 23


A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number.
A number n is called deficient if the sum of its proper divisors is less than n and it is called abundant if this sum exceeds n.
As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest number that can be written as the sum of two abundant numbers is 24. By mathematical analysis, it can be shown that all integers greater than 28123 can be written as the sum of two abundant numbers. However, this upper limit cannot be reduced any further by analysis even though it is known that the greatest number that cannot be expressed as the sum of two abundant numbers is less than this limit.
Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers.

My Solution Using Mathematica
MyList = Table[List[i, Total[Divisors[i]] - i], {i, 1, 28124}];
MyList = Select[MyList, #[[1]] < #[[2]] &]
MyList = MyList[[All, 1]]
SumoOfNumber = 0;
For[i = 1, i < 28124, i++, 
 If[Length[IntegerPartitions[i, {2}, MyList]] == 0, 
   SumoOfNumber = SumoOfNumber + i];]; Print[SumoOfNumber]

Everyday word 2009-09-16

nab vt.逮住; 捉住(某人)
lag n.滞后, (时间上的)间隔 vi.走得极慢; 落后
storefront n. 店面(房), 铺面(房); 临街房
petition n.(许多人签名的向当权者提出某种要求的)请愿书
wanker n. 手淫者;卑鄙的人
evangelism n. 福音传道,福音主义,福音传道者的工作
petal n.花瓣
buggy n.小机动车婴儿车轻便马车
detest vt.憎恶, 嫌恶, 痛恨
footage n.以英尺表示的长度或距离(电影或电视的)片段

Wednesday, September 9, 2009

Everyday word 2009-09-09

attic n.阁楼 顶楼
attorney n.律师
audacious adj.大胆的 愚勇的
augur n.占卜师
auspices n.资助
august adj.威严的,高贵的
augury n.语言 征兆
austere adj.朴素的
apparatus n.仪器 设备
archetype n.原型 典型例子

Euler Project 77


It is possible to write ten as the sum of primes in exactly five different ways:
7 + 3
5 + 5
5 + 3 + 2
3 + 3 + 2 + 2
2 + 2 + 2 + 2 + 2
What is the first value which can be written as the sum of primes in over five thousand different ways?


My Solution Using Mathematica
MyPrimesList = Table[Prime[i], {i, PrimePi[10000]}]

For[i = 2, i < 1000000, i++, 
 If[Length[IntegerPartitions[i, All, MyPrimesList]] > 5000, Print[i]; Break[]]]

Others' Solutions
First Solutions
(defun sieve (lst)
(let ((primes '())
(last (car (last lst))))
(loop while (and lst (> last (* (car lst) (car lst))))
do (let ((factor (car lst)))
(setq primes (cons factor primes))
(setq lst (remove-if
#'(lambda (n)
(= (mod n factor) 0))
(cdr lst)))))
(append (reverse primes) lst)))

(defun seq-list (min max)
(loop for i from min to max collect i))

(defun all-primes (limit)
(sieve (seq-list 2 limit)))

(defun fill-partitions-hash (max)
(setq partitions-hash (make-hash-table :test 'equal))
(setf (gethash (list 0 0) partitions-hash) 1)
(setf (gethash (list 1 1) partitions-hash) 0)
(loop for n from 1 to max
do (fill-partitions-helper n n)))

(defun fill-partitions-helper (n max)
(let ((memo (gethash (list n max) partitions-hash)))
(if memo
memo
(loop for i in all-primes
while (<= i max)
sum (fill-partitions-helper (- n i) (min i (- n i) max)) into p
finally (return (setf (gethash (list n max) partitions-hash) p))))))

(defun euler77 ()
(setq all-primes (all-primes 100))
(fill-partitions-hash 10)
(loop for i from 10
do (fill-partitions-helper i i)
if (> (gethash (list i i) partitions-hash) 5000)
return i)) 


Second Solution
Length@IntegerPartitions[n, n, Prime@Range@n]

Third Solution
(defun init-counts-table (n) 
    (let ((table (make-array (1+ n) :initial-element 0))) 
     table))
  
(defun update-counts-table! (table i n) 
    (incf (aref table i) 1) 
    (iterate loop ((c (+ 2 i))) 
        (unless (> c n) 
            (setf (aref table c) (lengthened-row-size table i c)) 
            (loop (1+ c)))))
  

(defun lengthened-row-size (table i c) 
    (let ((row-c (aref table c)) 
          (row-c-i (aref table (- c i)))) 
        (+ row-c-i row-c)))
  

(defun my-partition-counts.2 (n) 
    (let ((primes-vec (array-of-primes n)) 
          (table (init-counts-table n))) 
        (iterate loop ((i 0)) 
            (if (< i (array-dimension primes-vec 0)) 
                (let ((p (aref primes-vec i))) 
                    (update-counts-table! table p n) 
                    (loop (1+ i))))) 
        (aref table n)))

Tuesday, September 8, 2009

Application Role and Connection Pool

using (SqlConnection sqlCon = new SqlConnection(connectionString))

{

   
SqlCommand sqlCommand = new SqlCommand();
    sqlCommand
.Connection = sqlCon;
    sqlCommand
.CommandType = CommandType.Text;
    sqlCommand
.CommandText = "EXEC sp_setapprole 'application Role name','password';";
    sqlCommand
.CommandText += sqlComm;
    sqlCommand
.CommandTimeout = 300;
    sqlCon
.Open();
   int res = sqlCommand.ExecuteNonQuery();

}



This code is in a loop. for the first time, it's OK. In second iterator, it throws exception.
After a SQL Server application role has been activated by calling the sp_setapprole system stored procedure, the security context of that connection cannot be reset. However, if pooling is enabled, the connection is returned to the pool, and an error occurs when the pooled connection is reused.

If you are using SQL Server application roles, we recommend that you disable connection pooling for your application in the connection string.

Pooling can be disabled for the SQL Server .Net Data Provider by adding "Pooling=False" to the connection string.