Add example programs (project euler)

This commit is contained in:
Daniel M 2022-02-02 16:26:37 +01:00
parent c4b146c325
commit 86130984e2
5 changed files with 130 additions and 0 deletions

15
examples/euler1.nek Normal file
View File

@ -0,0 +1,15 @@
// 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.
//
// Correct Answer: 233168
sum <- 0;
i <- 0;
loop i < 1_000; i = i + 1 {
if i % 3 == 0 | i % 5 == 0 {
sum = sum + i;
}
}
print sum;

26
examples/euler2.nek Normal file
View File

@ -0,0 +1,26 @@
// Each new term in the Fibonacci sequence is generated by adding the previous two terms.
// By starting with 1 and 2, the first 10 terms will be:
// 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
// By considering the terms in the Fibonacci sequence whose values do not exceed four million,
// find the sum of the even-valued terms.
//
// Correct Answer: 4613732
sum <- 0;
a <- 0;
b <- 1;
tmp <- 0;
loop a < 4_000_000 {
if a % 2 == 0 {
sum = sum + a;
}
tmp = a;
a = b;
b = b + tmp;
}
print sum;

29
examples/euler3.nek Normal file
View File

@ -0,0 +1,29 @@
// The prime factors of 13195 are 5, 7, 13 and 29.
// What is the largest prime factor of the number 600851475143 ?
//
// Correct Answer: 6857
number <- 600_851_475_143;
result <- 0;
div <- 2;
loop number > 1 {
loop number % div == 0 {
if div > result {
result = div;
}
number = number / div;
}
div = div + 1;
if div * div > number {
if number > 1 & number > result {
result = number;
}
number = 0;
}
}
print result;

36
examples/euler4.nek Normal file
View File

@ -0,0 +1,36 @@
// A palindromic number reads the same both ways. The largest palindrome made from the product of
// two 2-digit numbers is 9009 = 91 × 99.
// Find the largest palindrome made from the product of two 3-digit numbers.
//
// Correct Answer: 906609
res <- 0;
tmp <- 0;
num <- 0;
num_rev <- 0;
i <- 100;
k <- 100;
loop i < 1_000; i = i + 1 {
k = 100;
loop k < 1_000; k = k + 1 {
num_rev = 0;
num = i * k;
tmp = num;
loop tmp {
num_rev = num_rev*10 + tmp % 10;
tmp = tmp / 10;
}
if num == num_rev & num > res {
res = num;
}
}
}
print res;

24
examples/euler4.py Normal file
View File

@ -0,0 +1,24 @@
# A palindromic number reads the same both ways. The largest palindrome made from the product of
# two 2-digit numbers is 9009 = 91 × 99.
# Find the largest palindrome made from the product of two 3-digit numbers.
#
# Correct Answer: 906609
res = 0
for i in range(100, 999):
for k in range(100, 999):
num = i * k
tmp = num
num_rev = 0
while tmp != 0:
num_rev = num_rev*10 + tmp % 10
tmp = tmp // 10
if num == num_rev and num > res:
res = num
print(res)