วันอาทิตย์ที่ 24 สิงหาคม พ.ศ. 2551

การหา factorial

การเขียนโปรแกรมหา factorial โดยทั่ว ๆ ไปสำหรับภาษาตระกูล imperative language จะต้องใช้ loop for
หรือใช้วิธีแบบ recursive เพื่อหาคำตอบ

แต่ถ้าเราเขียนโดยคิดแบบ function language จะลดทอนรูปลงมาโดยมีหน้าตาเช่นนี้ครับ
n = 10
print multiply.reduce(arange(1,n+1))


แต่จำนวนเต็มแบบ integer มีค่าไม่เกิน
2147483647

จึงต้องเพิ่มประเภทของจำนวนเต็มเป็น long จึงทำดังนี้ครับ
n = 20
print multiply.reduce(map(long,arange(1,20)))

121645100408832000


มีเพิ่มเติมเกี่ยวกับ functional programming ตรงนี้นิดหน่อย
http://gnosis.cx/publish/programming/charming_python_13.html
http://gnosis.cx/publish/programming/charming_python_16.html
http://gnosis.cx/publish/programming/charming_python_19.html

ไม่มีความคิดเห็น: