跳到主要內容

學程式設計的人不能不看的好文章

剛看到:學程式設計的人不能不看的好文章

原 創的大陸學生完全想錯方向,就像大一的電概作業計算1+2+...+n,一般人都用迴圈,而有數值分析經驗者就知道直接帶梯形公式(n+1)*n/2,演 算法比起任何pattern或技巧重要太多。現在的CPU速度快、RAM容量大,愈來愈少Programmer想要optimize,實在是很可惜呀~

而Vixual這篇有個回應,看到就知道這位仁兄真的懂C:

文章的範例最後還不夠精簡, 因為

1.奇偶數判斷, 使用 "取餘數的方式 (mod)" 太浪費時間
只要和 1 做 AND 運算即可

2.數字除 2, 使用 "除 2 (/ 2) 的方式" 太浪費時間
只要位元右移 1 次即可

3.正負數互換, 使用 "乘上 (-1) 的方式" 太浪費時間
只要 NOT 運算後再 + 1 即可

long fn(long n)
{
if (n <= 0)
{
printf("error: n must > 0");
exit(1);
}

if (n & 1) /* 奇數 */
return (~(n >> 1) + 1 + n);
else
return (~(n >> 1) + 1);
}

留言

鳥毅寫道…
再來個Java版
public class demo
{
static long fn(long n) throws Exception
{
if (n <= 0)
{
throw new Exception("error: n must > 0");
}

if ((n & 1)==1) /* 奇數 */
return (~(n >> 1) + n+1);
else
return (~(n >> 1)+1 );
}

public static void main(String [] args)
{
for(long nl=1; nl <= 20; nl++)
{
System.out.println(String.format("fn(%1$d)=%2$d\n", nl, fn(nl)));
//System.out.println(String.format("fn(%d)=%d\n", nl, fn(nl))); // C的Format寫法,效果相同
}
}
}
鳥毅寫道…
由於許多朋友說這個例子很好,因此加上CSharp版

using System;
public class demo
{
static long fn(long n)
{
if (n <= 0)
{
throw new Exception("error: n must > 0");
}

if ((n & 1)==1) /* 奇數 */
return (~(n >> 1) + n+1);
else
return (~(n >> 1)+1 );
}

public static void Main(string [] args)
{
for(long nl=1; nl <= 20; nl++)
Console.WriteLine(string.Format("fn({0})={1}\n", nl, fn(nl)));
}
}

這個網誌中的熱門文章

Personal Bookmark

Java SE 6 + Firefox 2 UI 問題 As I do . Google拋棄了了SOAP API,浮想聯翩 https://www.gandi.net/ VS 2005 SP1中文版推出 Windows Vista中文版下載 ASP.NET 2.0網頁執行管線與快取原理 Cache 2.0快取架構與快取資料自動移除架構圖 flickr sync 分享與試用 SUN Looking Glass 3D圖形介面發布1.0 雅虎勵精圖治推動改革 Wait and see 國內某SOC疑遭駭客入侵 大砲開講 Very Important! 微軟公佈Vista安全程式介面草案 一窺Google開原碼庫房乾坤 qing is writing a dig girl net... wait and see

DBeaver 介面語言

DBeaver是我個人頗常用的一套跨平台Database管理工具,最近升級後發現Windows版本居然變成簡體中文,而且無法切換為英文。

自然人憑證讀卡機驅動程式

鳥毅用的是第一代的自然人憑證讀卡機,EZ100PU(後來有同事買EZmini可以讀SIM卡似乎更好),每年報稅時用一次。 本來只是要申請些政府業務,一時之間找不到光碟,沒想到在 驅動程式下載 居然看到Linux和Mac的驅動程式,剩下的就是政府單位的網頁和程式應該改版了吧!!!