Skip to content

Instantly share code, notes, and snippets.

@axross
Last active August 29, 2015 14:24
Show Gist options
  • Save axross/82f7ae07e2e48570077c to your computer and use it in GitHub Desktop.
Save axross/82f7ae07e2e48570077c to your computer and use it in GitHub Desktop.
// 10未満の自然数のうち, 3 もしくは 5 の倍数になっているものは 3, 5, 6, 9 の4つがあり, これらの合計は 23 になる.
// 同じようにして, 1000 未満の 3 か 5 の倍数になっている数字の合計を求めよ.
const main = limit => {
let total = 0;
for (let i = 1; i < limit; ++i) {
if (i % 5 === 0) {
total += i;
} else if (i % 3 === 0) {
total += i;
}
}
return total;
};
const result = main(1000);
console.log(result);
// フィボナッチ数列の項は前の2つの項の和である. 最初の2項を 1, 2 とすれば, 最初の10項は以下の通りである.
// 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
// 数列の項の値が400万以下の, 偶数値の項の総和を求めよ.
// Note:この問題は最近更新されました. お使いのパラメータが正しいかどうか確認してください.
const fibonacciGenerator = function*(init = [0, 1]) {
let currentA = init[0];
let currentB = init[1];
while (true) {
const a = currentA;
const b = currentB;
const result = a + b;
currentA = b;
currentB = result;
yield { a, b, result };
}
};
const main = (max, init) => {
const gen = fibonacciGenerator(init);
let result = 0;
while (true) {
const value = gen.next().value;
if (value.a > max) break;
if (value.a % 2 === 0) {
result += value.a;
}
}
return result;
};
const result = main(4000000, [1, 2]);
console.log(result);
// 13195 の素因数は 5, 7, 13, 29 である.
// 600851475143 の素因数のうち最大のものを求めよ.
const computeMinimumPrime = number => {
for (let i = 2; i <= number; ++i) {
if (number % i === 0) return i;
}
return 0;
};
const computeAllPrimes = number => {
const primes = [];
let current = number;
while (true) {
const prime = computeMinimumPrime(current);
if (prime === 0) break;
current /= prime;
primes.push(prime);
}
return primes;
};
const result = computeAllPrimes(600851475143);
console.log(result[result.length - 1]);
// 左右どちらから読んでも同じ値になる数を回文数という. 2桁の数の積で表される回文数のうち, 最大のものは 9009 = 91 × 99 である.
// では, 3桁の数の積で表される回文数の最大値を求めよ.
const isPalindromic = value => {
for (let i = 0; i < Math.ceil(value.length / 2); ++i) {
if (value[i] !== value[value.length - 1 - i]) {
return false;
}
}
return true;
};
const cadentingProductGenerator = function*(first) {
for (let a = first; a > Math.floor(first / 2); --a) {
for (let b = first; b > Math.floor(first / 2); --b) {
yield a * b;
}
}
};
const main = digits => {
const palindromics = [];
const gen = cadentingProductGenerator(Math.pow(10, digits) - 1);
while (true) {
const result = gen.next();
const value = result.value;
if (isPalindromic(String(value)) && palindromics.indexOf(value) === -1) {
palindromics.push(value);
}
if (result.done) break;
}
return palindromics.reduce((a, b) => {
return b > a ? b : a;
}, 0);
};
const result = main(3);
console.log(result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment