程序2

【程序2】
题目:判断101-200之间有多少个素数,并输出所有素数。
1.程序分析:判断素数的方法:用一个数分别去除2到sqrt(这个数),如果能被整除,
则表明此数不是素数,反之是素数。

方法一:
        function primeInterval(start, end) {
            for (var i = start; i <= end; i++) {
                var flag = true;
                for (var j = 2; j <= Math.sqrt(i); j++) {
                    if (i % j === 0) {
                        flag = false;
                        break;
                    }
                }

                if (flag == true) {
                    document.write(i + "  ");
                }
            }
        }

        primeInterval(100, 200);

方法二:
        function isPrime(num) {
            var i, j;
            if (num === 2) {
                return true;
            }
            else if (num < 2 || num % 2 === 0) {
                return false;
            }
            else {
                j = parseInt(Math.sqrt(num + 1));
                for (i = 3; i <= j; i = i + 2) {
                    if (num % i === 0) {
                        return false;
                    }
                }
            }
            return true;
        }

        function primeInterval(start, end) {
            for (var i = start; i <= end; i++) {
                if (isPrime(i)) {
                    document.write(i + "   ");
                }
            }
        }

        primeInterval(100, 200);

posted @ 2012-05-29 00:32  前端咖  阅读(243)  评论(0编辑  收藏  举报