1. 程式人生 > >Problem1(Multiples of 3 and 5)

Problem1(Multiples of 3 and 5)

一.問題描述

      官方問題描述如下:

          If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.Find the sum of all the multiples of 3 or 5 below 1000.

      描述翻譯如下:

          如果我們列舉出所有小於10的自然數,並且它們是3或5的倍數,我們可以得到3,5,6和9.這些倍數的和是23.根據以上規律,找出所有小於1000的3或5倍數的和。


二.問題分析

     根據題目要求,解決問題的思想比較簡單,可以通過迴圈快速地計算出結果。但是,需要注意地是:

        對於小於1000的所有的自然數,它們可以分為四大類:

                  (1).既不是3的倍數,又不是5的倍數;

                  (2).雖是3的倍數,但不是5的倍數;

                  (3).雖是5的倍數,但不是3的倍數;

                  (4).既是3的倍數,又是5的倍數.

       顯然,(2).(3).(4)三部分組成的數集才是題目要求的數集.

三.問題解決

     1)Python解決問題  
#-*- coding:utf-8 -*-
#Multiples of 3 and 5   Python2.7  Windows 10
import time

def sumThreeAndFiveTimes(num):
	sum=0
	for i in xrange(1,num,1):
		if i%3==0 or i%5==0:
			sum+=i
	return sum

if __name__=="__main__":
	num=input("Please input a positive number :")
	start=time.clock() #計時開始
	print "The result is %d."%sumThreeAndFiveTimes(num) #獲得所求結果
	end=time.clock() #計時結束
	print "Time consumed is %f s."%(end-start) #輸出計算秒數
        輸出結果:

四.問題總結

     本問題的邏輯簡單明瞭,但是在程式設計過程中需要思考其中的小細節,避免產生不必要的漏洞。