Project Euler 1

Project Eulerというものを見つけました。
プログラムを使って解く数学の問題集、のようなものらしいです。登録をするときに、自分の国や使用する言語を入力します。
言語入力のところに「Pencil/Paper」って選択肢があるんだけど・・・

・・・。

Mathematicaの練習代わりにやってみようかなと。

それではさっそく第1問。

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の倍数を全て足した値を答えなさい。

Mathematica

A = 0;
For[i = 1 , i < 1000 , i++,
 If[
  IntegerQ[i/3] || IntegerQ[i/5],
   A += i
  , {}
  ]
 ]
A

我ながらひどいソースだ・・・*1


別解1

Plus @@ Select[Range@999, Mod[#, 3] == 0 || Mod[#, 5] == 0 &]


別解2

Tr[Union@@(#Range[999/#])]&@{3,5}

or just

Tr[3Range@333&#8899;5Range@199]


別解3

Tr[Select[Range[999],IntegerQ[#/3]==True&]]+ 
Tr[Select[Range[999],IntegerQ[#/5]==True&]]+ 
-Tr[Select[Range[999],IntegerQ[#/15]==True&]]

別解4

Sum[i, {i, 3, 999, 3}] + Sum[j, {j, 5, 999, 5}] - Sum[j, {j, 15, 999, 15}]


#や@の使い方がまだよくわかりません・・・別解4がわかりやすくていいですね。

C/C++

C/C++の練習もすることにしました。

#include <iostream>

using namespace std;

int main(){
	
	int ans = 0;

	for( int i=1 ; i<1000 ; i++){
		if(i%3==0 || i%5==0) ans += i;
	}

	cout << ans << endl;

	return 0;
}

軽いリハビリ。さくさくかけて楽しいな、C++!簡単だからですけど・・・

*1:IntegerQ[expr]: 式exprが整数の場合にTrueを,その他の場合Falseを返す。