task_url
stringlengths 30
116
| task_name
stringlengths 2
86
| task_description
stringlengths 0
14.4k
| language_url
stringlengths 2
53
| language_name
stringlengths 1
52
| code
stringlengths 0
61.9k
|
---|---|---|---|---|---|
http://rosettacode.org/wiki/Greatest_common_divisor
|
Greatest common divisor
|
Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related task
least common multiple.
See also
MathWorld entry: greatest common divisor.
Wikipedia entry: greatest common divisor.
|
#LFE
|
LFE
|
> (defun gcd
"Get the greatest common divisor."
((a 0) a)
((a b) (gcd b (rem a b))))
|
http://rosettacode.org/wiki/Hailstone_sequence
|
Hailstone sequence
|
The Hailstone sequence of numbers can be generated from a starting positive integer, n by:
If n is 1 then the sequence ends.
If n is even then the next n of the sequence = n/2
If n is odd then the next n of the sequence = (3 * n) + 1
The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates.
This sequence was named by Lothar Collatz in 1937 (or possibly in 1939), and is also known as (the):
hailstone sequence, hailstone numbers
3x + 2 mapping, 3n + 1 problem
Collatz sequence
Hasse's algorithm
Kakutani's problem
Syracuse algorithm, Syracuse problem
Thwaites conjecture
Ulam's problem
The hailstone sequence is also known as hailstone numbers (because the values are usually subject to multiple descents and ascents like hailstones in a cloud).
Task
Create a routine to generate the hailstone sequence for a number.
Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1
Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.
(But don't show the actual sequence!)
See also
xkcd (humourous).
The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).
The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).
|
#MATLAB_.2F_Octave
|
MATLAB / Octave
|
function x = hailstone(n)
x = n;
while n > 1
% faster than mod(n, 2)
if n ~= floor(n / 2) * 2
n = n * 3 + 1;
else
n = n / 2;
end
x(end + 1) = n; %#ok
end
|
http://rosettacode.org/wiki/Happy_numbers
|
Happy numbers
|
From Wikipedia, the free encyclopedia:
A happy number is defined by the following process:
Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.
Those numbers for which this process end in 1 are happy numbers,
while those numbers that do not end in 1 are unhappy numbers.
Task
Find and print the first 8 happy numbers.
Display an example of your output here on this page.
See also
The OEIS entry: The happy numbers: A007770
The OEIS entry: The unhappy numbers; A031177
|
#TUSCRIPT
|
TUSCRIPT
|
$$ MODE TUSCRIPT
SECTION check
IF (n!=1) THEN
n = STRINGS (n,":>/:")
LOOP/CLEAR nr=n
square=nr*nr
n=APPEND (n,square)
ENDLOOP
n=SUM(n)
r_table=QUOTES (n)
BUILD R_TABLE/word/EXACT chk=r_table
IF (seq.ma.chk) THEN
status="next"
ELSE
seq=APPEND (seq,n)
ENDIF
RELEASE r_table chk
ELSE
PRINT checkednr," is a happy number"
happynrs=APPEND (happynrs,checkednr)
status="next"
ENDIF
ENDSECTION
happynrs=""
LOOP n=1,100
sz_happynrs=SIZE(happynrs)
IF (sz_happynrs==8) EXIT
checkednr=VALUE(n)
status=seq=""
LOOP
IF (status=="next") EXIT
DO check
ENDLOOP
ENDLOOP
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#LotusScript
|
LotusScript
|
:- object(hello_world).
'This will send the output to the status bar at the bottom of the Notes client screen
print "Hello world!"
:- end_object.
|
http://rosettacode.org/wiki/Generic_swap
|
Generic swap
|
Task
Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types.
If your solution language is statically typed please describe the way your language provides genericity.
If variables are typed in the given language, it is permissible that the two variables be constrained to having a mutually compatible type, such that each is permitted to hold the value previously stored in the other without a type violation.
That is to say, solutions do not have to be capable of exchanging, say, a string and integer value, if the underlying storage locations are not attributed with types that permit such an exchange.
Generic swap is a task which brings together a few separate issues in programming language semantics.
Dynamically typed languages deal with values in a generic way quite readily, but do not necessarily make it easy to write a function to destructively swap two variables, because this requires indirection upon storage places or upon the syntax designating storage places.
Functional languages, whether static or dynamic, do not necessarily allow a destructive operation such as swapping two variables regardless of their generic capabilities.
Some static languages have difficulties with generic programming due to a lack of support for (Parametric Polymorphism).
Do your best!
|
#Logo
|
Logo
|
to swap :s1 :s2
localmake "t thing :s1
make :s1 thing :s2
make :s2 :t
end
make "a 4
make "b "dog
swap "a "b ; pass the names of the variables to swap
show list :a :b ; [dog 4]
|
http://rosettacode.org/wiki/Greatest_element_of_a_list
|
Greatest element of a list
|
Task
Create a function that returns the maximum value in a provided set of values,
where the number of values may not be known until run-time.
|
#NewLISP
|
NewLISP
|
(max 1 2 3 5 2 3 4)
|
http://rosettacode.org/wiki/Greatest_element_of_a_list
|
Greatest element of a list
|
Task
Create a function that returns the maximum value in a provided set of values,
where the number of values may not be known until run-time.
|
#Nial
|
Nial
|
max 1 2 3 4
=4
|
http://rosettacode.org/wiki/Greatest_common_divisor
|
Greatest common divisor
|
Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related task
least common multiple.
See also
MathWorld entry: greatest common divisor.
Wikipedia entry: greatest common divisor.
|
#Liberty_BASIC
|
Liberty BASIC
|
'iterative Euclid algorithm
print GCD(-2,16)
end
function GCD(a,b)
while b
c = a
a = b
b = c mod b
wend
GCD = abs(a)
end function
|
http://rosettacode.org/wiki/Hailstone_sequence
|
Hailstone sequence
|
The Hailstone sequence of numbers can be generated from a starting positive integer, n by:
If n is 1 then the sequence ends.
If n is even then the next n of the sequence = n/2
If n is odd then the next n of the sequence = (3 * n) + 1
The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates.
This sequence was named by Lothar Collatz in 1937 (or possibly in 1939), and is also known as (the):
hailstone sequence, hailstone numbers
3x + 2 mapping, 3n + 1 problem
Collatz sequence
Hasse's algorithm
Kakutani's problem
Syracuse algorithm, Syracuse problem
Thwaites conjecture
Ulam's problem
The hailstone sequence is also known as hailstone numbers (because the values are usually subject to multiple descents and ascents like hailstones in a cloud).
Task
Create a routine to generate the hailstone sequence for a number.
Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1
Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.
(But don't show the actual sequence!)
See also
xkcd (humourous).
The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).
The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).
|
#Maxima
|
Maxima
|
collatz(n) := block([L], L: [n], while n > 1 do
(n: if evenp(n) then n/2 else 3*n + 1, L: endcons(n, L)), L)$
collatz_length(n) := block([m], m: 1, while n > 1 do
(n: if evenp(n) then n/2 else 3*n + 1, m: m + 1), m)$
collatz_max(n) := block([j, m, p], m: 0,
for i from 1 thru n do
(p: collatz_length(i), if p > m then (m: p, j: i)),
[j, m])$
collatz(27); /* [27, 82, 41, ..., 4, 2, 1] */
length(%); /* 112 */
collatz_length(27); /* 112 */
collatz_max(100000); /* [77031, 351] */
|
http://rosettacode.org/wiki/Happy_numbers
|
Happy numbers
|
From Wikipedia, the free encyclopedia:
A happy number is defined by the following process:
Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.
Those numbers for which this process end in 1 are happy numbers,
while those numbers that do not end in 1 are unhappy numbers.
Task
Find and print the first 8 happy numbers.
Display an example of your output here on this page.
See also
The OEIS entry: The happy numbers: A007770
The OEIS entry: The unhappy numbers; A031177
|
#uBasic.2F4tH
|
uBasic/4tH
|
' ************************
' MAIN
' ************************
PROC _PRINT_HAPPY(20)
END
' ************************
' END MAIN
' ************************
' ************************
' SUBS & FUNCTIONS
' ************************
' --------------------
_is_happy PARAM(1)
' --------------------
LOCAL (5)
f@ = 100
c@ = a@
b@ = 0
DO WHILE b@ < f@
e@ = 0
DO WHILE c@
d@ = c@ % 10
c@ = c@ / 10
e@ = e@ + (d@ * d@)
LOOP
UNTIL e@ = 1
c@ = e@
b@ = b@ + 1
LOOP
RETURN(b@ < f@)
' --------------------
_PRINT_HAPPY PARAM(1)
' --------------------
LOCAL (2)
b@ = 1
c@ = 0
DO
IF FUNC (_is_happy(b@)) THEN
c@ = c@ + 1
PRINT b@
ENDIF
b@ = b@ + 1
UNTIL c@ + 1 > a@
LOOP
RETURN
' ************************
' END SUBS & FUNCTIONS
' ************************
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#LSE
|
LSE
|
AFFICHER [U, /] 'Hello world!'
|
http://rosettacode.org/wiki/Generic_swap
|
Generic swap
|
Task
Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types.
If your solution language is statically typed please describe the way your language provides genericity.
If variables are typed in the given language, it is permissible that the two variables be constrained to having a mutually compatible type, such that each is permitted to hold the value previously stored in the other without a type violation.
That is to say, solutions do not have to be capable of exchanging, say, a string and integer value, if the underlying storage locations are not attributed with types that permit such an exchange.
Generic swap is a task which brings together a few separate issues in programming language semantics.
Dynamically typed languages deal with values in a generic way quite readily, but do not necessarily make it easy to write a function to destructively swap two variables, because this requires indirection upon storage places or upon the syntax designating storage places.
Functional languages, whether static or dynamic, do not necessarily allow a destructive operation such as swapping two variables regardless of their generic capabilities.
Some static languages have difficulties with generic programming due to a lack of support for (Parametric Polymorphism).
Do your best!
|
#Logtalk
|
Logtalk
|
:- object(paws).
:- public(swap/4).
swap(First, Second, Second, First).
:- end_object.
|
http://rosettacode.org/wiki/Greatest_element_of_a_list
|
Greatest element of a list
|
Task
Create a function that returns the maximum value in a provided set of values,
where the number of values may not be known until run-time.
|
#Nim
|
Nim
|
echo max([2,3,4,5,6,1])
|
http://rosettacode.org/wiki/Greatest_element_of_a_list
|
Greatest element of a list
|
Task
Create a function that returns the maximum value in a provided set of values,
where the number of values may not be known until run-time.
|
#Oberon-2
|
Oberon-2
|
MODULE GreatestElement1;
IMPORT
ADT:ArrayList,
Object:Boxed,
Out;
VAR
a: ArrayList.ArrayList(Boxed.LongInt);
max: Boxed.LongInt;
PROCEDURE Max(al: ArrayList.ArrayList(Boxed.LongInt)): Boxed.LongInt;
VAR
i: LONGINT;
item, max: Boxed.LongInt;
BEGIN
max := NEW(Boxed.LongInt,MIN(LONGINT));
i := 0;
WHILE (i < al.size) DO
item := al.Get(i);
IF item.value > max.value THEN max := item END;
INC(i)
END;
RETURN max
END Max;
BEGIN
a := NEW(ArrayList.ArrayList(Boxed.LongInt),5);
a.Append(NEW(Boxed.LongInt,10));
a.Append(NEW(Boxed.LongInt,32));
a.Append(NEW(Boxed.LongInt,4));
a.Append(NEW(Boxed.LongInt,43));
a.Append(NEW(Boxed.LongInt,9));
max := Max(a);
Out.String("Max: ");Out.LongInt(max.value,4);Out.Ln
END GreatestElement1.
|
http://rosettacode.org/wiki/Greatest_common_divisor
|
Greatest common divisor
|
Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related task
least common multiple.
See also
MathWorld entry: greatest common divisor.
Wikipedia entry: greatest common divisor.
|
#Limbo
|
Limbo
|
gcd(x: int, y: int): int
{
if(y == 0)
return x;
return gcd(y, x % y);
}
|
http://rosettacode.org/wiki/Greatest_common_divisor
|
Greatest common divisor
|
Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related task
least common multiple.
See also
MathWorld entry: greatest common divisor.
Wikipedia entry: greatest common divisor.
|
#LiveCode
|
LiveCode
|
function gcd x,y
repeat until y = 0
put x mod y into z
put y into x
put z into y
end repeat
return x
end gcd
|
http://rosettacode.org/wiki/Hailstone_sequence
|
Hailstone sequence
|
The Hailstone sequence of numbers can be generated from a starting positive integer, n by:
If n is 1 then the sequence ends.
If n is even then the next n of the sequence = n/2
If n is odd then the next n of the sequence = (3 * n) + 1
The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates.
This sequence was named by Lothar Collatz in 1937 (or possibly in 1939), and is also known as (the):
hailstone sequence, hailstone numbers
3x + 2 mapping, 3n + 1 problem
Collatz sequence
Hasse's algorithm
Kakutani's problem
Syracuse algorithm, Syracuse problem
Thwaites conjecture
Ulam's problem
The hailstone sequence is also known as hailstone numbers (because the values are usually subject to multiple descents and ascents like hailstones in a cloud).
Task
Create a routine to generate the hailstone sequence for a number.
Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1
Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.
(But don't show the actual sequence!)
See also
xkcd (humourous).
The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).
The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).
|
#Mercury
|
Mercury
|
:- module hailstone.
:- interface.
:- import_module int, list.
:- func hailstone(int) = list(int).
:- pred hailstone(int::in, list(int)::out) is det.
:- implementation.
hailstone(N) = S :- hailstone(N, S).
hailstone(N, [N|S]) :-
( N = 1 -> S = []
; N mod 2 = 0 -> hailstone(N/2, S)
; hailstone(3 * N + 1, S) ).
:- end_module hailstone.
|
http://rosettacode.org/wiki/Happy_numbers
|
Happy numbers
|
From Wikipedia, the free encyclopedia:
A happy number is defined by the following process:
Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.
Those numbers for which this process end in 1 are happy numbers,
while those numbers that do not end in 1 are unhappy numbers.
Task
Find and print the first 8 happy numbers.
Display an example of your output here on this page.
See also
The OEIS entry: The happy numbers: A007770
The OEIS entry: The unhappy numbers; A031177
|
#UNIX_Shell
|
UNIX Shell
|
#!/bin/bash
function sum_of_square_digits
{
local -i n="$1" sum=0
while (( n )); do
local -i d=n%10
let sum+=d*d
let n=n/10
done
echo "$sum"
}
function is_happy?
{
local -i n="$1"
local seen=()
while (( n != 1 )); do
if [ -n "${seen[$n]}" ]; then
return 1
fi
seen[n]=1
let n="$(sum_of_square_digits "$n")"
done
return 0
}
function first_n_happy
{
local -i count="$1"
local -i n
for (( n=0; count; n+=1 )); do
if is_happy? "$n"; then
echo "$n"
let count-=1
fi
done
return 0
}
first_n_happy 8
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#LSE64
|
LSE64
|
"Hello world!" ,t nl
|
http://rosettacode.org/wiki/Generic_swap
|
Generic swap
|
Task
Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types.
If your solution language is statically typed please describe the way your language provides genericity.
If variables are typed in the given language, it is permissible that the two variables be constrained to having a mutually compatible type, such that each is permitted to hold the value previously stored in the other without a type violation.
That is to say, solutions do not have to be capable of exchanging, say, a string and integer value, if the underlying storage locations are not attributed with types that permit such an exchange.
Generic swap is a task which brings together a few separate issues in programming language semantics.
Dynamically typed languages deal with values in a generic way quite readily, but do not necessarily make it easy to write a function to destructively swap two variables, because this requires indirection upon storage places or upon the syntax designating storage places.
Functional languages, whether static or dynamic, do not necessarily allow a destructive operation such as swapping two variables regardless of their generic capabilities.
Some static languages have difficulties with generic programming due to a lack of support for (Parametric Polymorphism).
Do your best!
|
#LOLCODE
|
LOLCODE
|
HAI 1.3
I HAS A foo ITZ "kittehz"
I HAS A bar ITZ 42
foo, foo R bar, bar R IT
VISIBLE foo BTW, 42
VISIBLE bar BTW, kittehz
KTHXBYE
|
http://rosettacode.org/wiki/Greatest_element_of_a_list
|
Greatest element of a list
|
Task
Create a function that returns the maximum value in a provided set of values,
where the number of values may not be known until run-time.
|
#Objeck
|
Objeck
|
values := IntVector->New([4, 1, 42, 5]);
values->Max()->PrintLine();
|
http://rosettacode.org/wiki/Greatest_element_of_a_list
|
Greatest element of a list
|
Task
Create a function that returns the maximum value in a provided set of values,
where the number of values may not be known until run-time.
|
#Objective-C
|
Objective-C
|
#import <Foundation/Foundation.h>
@interface NSArray (WithMaximum)
- (id)maximumValue;
@end
@implementation NSArray (WithMaximum)
- (id)maximumValue
{
if ( [self count] == 0 ) return nil;
id maybeMax = self[0];
for ( id el in self ) {
if ( [maybeMax respondsToSelector: @selector(compare:)] &&
[el respondsToSelector: @selector(compare:)] &&
[el isKindOfClass: [NSNumber class]] &&
[maybeMax isKindOfClass: [NSNumber class]] ) {
if ( [maybeMax compare: el] == NSOrderedAscending )
maybeMax = el;
} else { return nil; }
}
return maybeMax;
}
@end
|
http://rosettacode.org/wiki/Greatest_common_divisor
|
Greatest common divisor
|
Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related task
least common multiple.
See also
MathWorld entry: greatest common divisor.
Wikipedia entry: greatest common divisor.
|
#Logo
|
Logo
|
to gcd :a :b
if :b = 0 [output :a]
output gcd :b modulo :a :b
end
|
http://rosettacode.org/wiki/Greatest_common_divisor
|
Greatest common divisor
|
Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related task
least common multiple.
See also
MathWorld entry: greatest common divisor.
Wikipedia entry: greatest common divisor.
|
#LOLCODE
|
LOLCODE
|
HAI 1.3
HOW IZ I gcd YR a AN YR b
a R BIGGR OF a AN PRODUKT OF a AN -1 BTW absolute value of a
b R BIGGR OF b AN PRODUKT OF b AN -1 BTW absolute value of b
BOTH SAEM a AN b, O RLY?
YA RLY
FOUND YR a
OIC
BOTH SAEM a AN 0, O RLY?
YA RLY
FOUND YR b
OIC
BOTH SAEM b AN 0, O RLY?
YA RLY
FOUND YR a
OIC
BOTH SAEM b AN BIGGR OF a AN b, O RLY? BTW make sure a is the larger of (a, b)
YA RLY
I HAS A temp ITZ a
a R b
b R temp
OIC
IM IN YR LOOP
I HAS A temp ITZ b
b R MOD OF a AN b
a R temp
BOTH SAEM b AN 0, O RLY?
YA RLY
FOUND YR a
OIC
IM OUTTA YR LOOP
IF U SAY SO
VISIBLE I IZ gcd YR 40902 AN YR 24140 MKAY
KTHXBYE
|
http://rosettacode.org/wiki/Hailstone_sequence
|
Hailstone sequence
|
The Hailstone sequence of numbers can be generated from a starting positive integer, n by:
If n is 1 then the sequence ends.
If n is even then the next n of the sequence = n/2
If n is odd then the next n of the sequence = (3 * n) + 1
The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates.
This sequence was named by Lothar Collatz in 1937 (or possibly in 1939), and is also known as (the):
hailstone sequence, hailstone numbers
3x + 2 mapping, 3n + 1 problem
Collatz sequence
Hasse's algorithm
Kakutani's problem
Syracuse algorithm, Syracuse problem
Thwaites conjecture
Ulam's problem
The hailstone sequence is also known as hailstone numbers (because the values are usually subject to multiple descents and ascents like hailstones in a cloud).
Task
Create a routine to generate the hailstone sequence for a number.
Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1
Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.
(But don't show the actual sequence!)
See also
xkcd (humourous).
The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).
The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).
|
#ML
|
ML
|
fun hail (x = 1) = [1]
| (x rem 2 = 0) = x :: hail (x div 2)
| x = x :: hail (x * 3 + 1)
fun hailstorm
([], i, largest, largest_at) = (largest_at, largest)
| (x :: xs, i, largest, largest_at) =
let
val k = len (hail x)
in
if k > largest then
hailstorm (xs, i + 1, k, i)
else
hailstorm (xs, i + 1, largest, largest_at)
end
| (x :: xs) = hailstorm (x :: xs, 1, 0, 0)
;
val h27 = hail 27;
print "hailstone sequence for the number 27 has ";
print ` len (h27);
print " elements starting with ";
print ` sub (h27, 0, 4);
print " and ending with ";
print ` sub (h27, len(h27)-4, len h27);
println ".";
val biggest = hailstorm ` iota (100000 - 1);
print "The number less than 100,000 which has the longest ";
print "hailstone sequence is at element ";
print ` ref (biggest, 0);
print " and is of length ";
println ` ref (biggest, 1);
|
http://rosettacode.org/wiki/Happy_numbers
|
Happy numbers
|
From Wikipedia, the free encyclopedia:
A happy number is defined by the following process:
Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.
Those numbers for which this process end in 1 are happy numbers,
while those numbers that do not end in 1 are unhappy numbers.
Task
Find and print the first 8 happy numbers.
Display an example of your output here on this page.
See also
The OEIS entry: The happy numbers: A007770
The OEIS entry: The unhappy numbers; A031177
|
#Ursala
|
Ursala
|
#import std
#import nat
happy = ==1+ ^== sum:-0+ product*iip+ %np*hiNCNCS+ %nP
first "p" = ~&i&& iota; ~&lrtPX/&; leql@lrPrX->lrx ^|\~& ^/successor@l ^|T\~& "p"&& ~&iNC
#cast %nL
main = (first happy) 8
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#Lua
|
Lua
|
print "Hello world!"
|
http://rosettacode.org/wiki/Generic_swap
|
Generic swap
|
Task
Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types.
If your solution language is statically typed please describe the way your language provides genericity.
If variables are typed in the given language, it is permissible that the two variables be constrained to having a mutually compatible type, such that each is permitted to hold the value previously stored in the other without a type violation.
That is to say, solutions do not have to be capable of exchanging, say, a string and integer value, if the underlying storage locations are not attributed with types that permit such an exchange.
Generic swap is a task which brings together a few separate issues in programming language semantics.
Dynamically typed languages deal with values in a generic way quite readily, but do not necessarily make it easy to write a function to destructively swap two variables, because this requires indirection upon storage places or upon the syntax designating storage places.
Functional languages, whether static or dynamic, do not necessarily allow a destructive operation such as swapping two variables regardless of their generic capabilities.
Some static languages have difficulties with generic programming due to a lack of support for (Parametric Polymorphism).
Do your best!
|
#Lua
|
Lua
|
x, y = y, x -- swap the values inside x and y
t[1], t[2] = t[2], t[1] -- swap the first and second values inside table t
|
http://rosettacode.org/wiki/Greatest_element_of_a_list
|
Greatest element of a list
|
Task
Create a function that returns the maximum value in a provided set of values,
where the number of values may not be known until run-time.
|
#OCaml
|
OCaml
|
let my_max = function
[] -> invalid_arg "empty list"
| x::xs -> List.fold_left max x xs
|
http://rosettacode.org/wiki/Greatest_element_of_a_list
|
Greatest element of a list
|
Task
Create a function that returns the maximum value in a provided set of values,
where the number of values may not be known until run-time.
|
#Octave
|
Octave
|
m = max( [1,2,3,20,10,9,8] ); % m = 20
[m, im] = max( [1,2,3,20,10,9,8] ); % im = 4
|
http://rosettacode.org/wiki/Greatest_common_divisor
|
Greatest common divisor
|
Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related task
least common multiple.
See also
MathWorld entry: greatest common divisor.
Wikipedia entry: greatest common divisor.
|
#LSE
|
LSE
|
(*
** MÉTHODE D'EUCLIDE POUR TROUVER LE PLUS GRAND DIVISEUR COMMUN D'UN
** NUMÉRATEUR ET D'UN DÉNOMINATEUR.
*)
PROCÉDURE &PGDC(ENTIER U, ENTIER V) : ENTIER LOCAL U, V
ENTIER T
TANT QUE U > 0 FAIRE
SI U< V ALORS
T<-U
U<-V
V<-T
FIN SI
U <- U - V
BOUCLER
RÉSULTAT V
FIN PROCÉDURE
PROCÉDURE &DEMO(ENTIER U, ENTIER V) LOCAL U, V
AFFICHER ['Le PGDC de ',U,'/',U,' est ',U,/] U, V, &PGDC(U,V)
FIN PROCÉDURE
&DEMO(9,12)
&DEMO(6144,8192)
&DEMO(100,5)
&DEMO(7,23)
|
http://rosettacode.org/wiki/Greatest_common_divisor
|
Greatest common divisor
|
Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related task
least common multiple.
See also
MathWorld entry: greatest common divisor.
Wikipedia entry: greatest common divisor.
|
#Lua
|
Lua
|
function gcd(a,b)
if b ~= 0 then
return gcd(b, a % b)
else
return math.abs(a)
end
end
function demo(a,b)
print("GCD of " .. a .. " and " .. b .. " is " .. gcd(a, b))
end
demo(100, 5)
demo(5, 100)
demo(7, 23)
|
http://rosettacode.org/wiki/Hailstone_sequence
|
Hailstone sequence
|
The Hailstone sequence of numbers can be generated from a starting positive integer, n by:
If n is 1 then the sequence ends.
If n is even then the next n of the sequence = n/2
If n is odd then the next n of the sequence = (3 * n) + 1
The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates.
This sequence was named by Lothar Collatz in 1937 (or possibly in 1939), and is also known as (the):
hailstone sequence, hailstone numbers
3x + 2 mapping, 3n + 1 problem
Collatz sequence
Hasse's algorithm
Kakutani's problem
Syracuse algorithm, Syracuse problem
Thwaites conjecture
Ulam's problem
The hailstone sequence is also known as hailstone numbers (because the values are usually subject to multiple descents and ascents like hailstones in a cloud).
Task
Create a routine to generate the hailstone sequence for a number.
Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1
Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.
(But don't show the actual sequence!)
See also
xkcd (humourous).
The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).
The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).
|
#Modula-2
|
Modula-2
|
MODULE hailst;
IMPORT InOut;
CONST maxCard = MAX (CARDINAL) DIV 3;
TYPE action = (List, Count, Max);
VAR a : CARDINAL;
PROCEDURE HailStone (start : CARDINAL; type : action) : CARDINAL;
VAR n, max, count : CARDINAL;
BEGIN
count := 1;
n := start;
max := n;
LOOP
IF type = List THEN
InOut.WriteCard (n, 12);
IF count MOD 6 = 0 THEN InOut.WriteLn END
END;
IF n = 1 THEN EXIT END;
IF ODD (n) THEN
IF n < maxCard THEN
n := 3 * n + 1;
IF n > max THEN max := n END
ELSE
InOut.WriteString ("Exceeding max value for type CARDINAL at count = ");
InOut.WriteCard (count, 10);
InOut.WriteString (" for intermediate value ");
InOut.WriteCard (n, 10);
InOut.WriteString (". Aborting.");
HALT
END
ELSE
n := n DIV 2
END;
INC (count)
END;
IF type = Max THEN RETURN max ELSE RETURN count END
END HailStone;
PROCEDURE FindMax (num : CARDINAL);
VAR val, maxCount, maxVal, cnt : CARDINAL;
BEGIN
maxCount := 0;
maxVal := 0;
FOR val := 2 TO num DO
cnt := HailStone (val, Count);
IF cnt > maxCount THEN
maxVal := val;
maxCount := cnt
END
END;
InOut.WriteString ("Longest sequence below "); InOut.WriteCard (num, 1);
InOut.WriteString (" is "); InOut.WriteCard (HailStone (maxVal, Count), 1);
InOut.WriteString (" for n = "); InOut.WriteCard (maxVal, 1);
InOut.WriteString (" with an intermediate maximum of ");
InOut.WriteCard (HailStone (maxVal, Max), 1);
InOut.WriteLn
END FindMax;
BEGIN
a := HailStone (27, List);
InOut.WriteLn;
InOut.WriteString ("Iterations total = "); InOut.WriteCard (HailStone (27, Count), 12);
InOut.WriteString (" max value = "); InOut.WriteCard (HailStone (27, Max) , 12);
InOut.WriteLn;
FindMax (100000);
InOut.WriteString ("Done."); InOut.WriteLn
END hailst.
|
http://rosettacode.org/wiki/Happy_numbers
|
Happy numbers
|
From Wikipedia, the free encyclopedia:
A happy number is defined by the following process:
Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.
Those numbers for which this process end in 1 are happy numbers,
while those numbers that do not end in 1 are unhappy numbers.
Task
Find and print the first 8 happy numbers.
Display an example of your output here on this page.
See also
The OEIS entry: The happy numbers: A007770
The OEIS entry: The unhappy numbers; A031177
|
#Vala
|
Vala
|
using Gee;
/* function to sum the square of the digits */
int sum(int input){
// convert input int to string
string input_str = input.to_string();
int total = 0;
// read through each character in string, square them and add to total
for (int x = 0; x < input_str.length; x++){
// char.digit_value converts char to the decimal value the char it represents holds
int digit = input_str[x].digit_value();
total += (digit * digit);
}
return total;
} // end sum
/* function to decide if a number is a happy number */
bool is_happy(int total){
var past = new HashSet<int>();
while(true){
total = sum(total);
if (total == 1){
return true;}
if (total in past){
return false;}
past.add(total);
} // end while loop
} // end happy
public static void main(){
var happynums = new ArrayList<int>();
int x = 1;
while (happynums.size < 8){
if (is_happy(x) == true)
happynums.add(x);
x++;
}
foreach(int num in happynums)
stdout.printf("%d ", num);
stdout.printf("\n");
} // end main
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#Luna
|
Luna
|
def main:
hello = "Hello, World!"
print hello
|
http://rosettacode.org/wiki/Generic_swap
|
Generic swap
|
Task
Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types.
If your solution language is statically typed please describe the way your language provides genericity.
If variables are typed in the given language, it is permissible that the two variables be constrained to having a mutually compatible type, such that each is permitted to hold the value previously stored in the other without a type violation.
That is to say, solutions do not have to be capable of exchanging, say, a string and integer value, if the underlying storage locations are not attributed with types that permit such an exchange.
Generic swap is a task which brings together a few separate issues in programming language semantics.
Dynamically typed languages deal with values in a generic way quite readily, but do not necessarily make it easy to write a function to destructively swap two variables, because this requires indirection upon storage places or upon the syntax designating storage places.
Functional languages, whether static or dynamic, do not necessarily allow a destructive operation such as swapping two variables regardless of their generic capabilities.
Some static languages have difficulties with generic programming due to a lack of support for (Parametric Polymorphism).
Do your best!
|
#M2000_Interpreter
|
M2000 Interpreter
|
\\ pgramming again Swap (for local use)
Module Swap (&a, &b) {
\\ this call internal command - by default is by reference without using character &
Swap a, b
}
X=20
Y=100
Swap &x, &y
Print X, Y, Type$(X)="Double",Type$(Y)="Double"
A$="A$"
B$="B$"
Swap &A$, &B$
Print A$="B$", B$="A$"
|
http://rosettacode.org/wiki/Greatest_element_of_a_list
|
Greatest element of a list
|
Task
Create a function that returns the maximum value in a provided set of values,
where the number of values may not be known until run-time.
|
#Oforth
|
Oforth
|
[1, 2.3, 5.6, 1, 3, 4 ] reduce(#max)
|
http://rosettacode.org/wiki/Greatest_element_of_a_list
|
Greatest element of a list
|
Task
Create a function that returns the maximum value in a provided set of values,
where the number of values may not be known until run-time.
|
#Ol
|
Ol
|
; builtin function
(max 1 2 3 4 5) ; 5
(define x '(1 2 3 4 5))
; using to numbers list
(apply max x) ; 5
; using list reducing
(fold max (car x) x) ; 5
; manual lambda-comparator
(print (fold (lambda (a b)
(if (less? a b) b a))
(car x) x)) ; 5
|
http://rosettacode.org/wiki/Greatest_common_divisor
|
Greatest common divisor
|
Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related task
least common multiple.
See also
MathWorld entry: greatest common divisor.
Wikipedia entry: greatest common divisor.
|
#Lucid
|
Lucid
|
gcd(n,m) where
z = [% n, m %] fby if x > y then [% x - y, y %] else [% x, y - x%] fi;
x = hd(z);
y = hd(tl(z));
gcd(n, m) = (x asa x*y eq 0) fby eod;
end
|
http://rosettacode.org/wiki/Greatest_common_divisor
|
Greatest common divisor
|
Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related task
least common multiple.
See also
MathWorld entry: greatest common divisor.
Wikipedia entry: greatest common divisor.
|
#Luck
|
Luck
|
function gcd(a: int, b: int): int = (
if a==0 then b
else if b==0 then a
else if a>b then gcd(b, a % b)
else gcd(a, b % a)
)
|
http://rosettacode.org/wiki/Hailstone_sequence
|
Hailstone sequence
|
The Hailstone sequence of numbers can be generated from a starting positive integer, n by:
If n is 1 then the sequence ends.
If n is even then the next n of the sequence = n/2
If n is odd then the next n of the sequence = (3 * n) + 1
The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates.
This sequence was named by Lothar Collatz in 1937 (or possibly in 1939), and is also known as (the):
hailstone sequence, hailstone numbers
3x + 2 mapping, 3n + 1 problem
Collatz sequence
Hasse's algorithm
Kakutani's problem
Syracuse algorithm, Syracuse problem
Thwaites conjecture
Ulam's problem
The hailstone sequence is also known as hailstone numbers (because the values are usually subject to multiple descents and ascents like hailstones in a cloud).
Task
Create a routine to generate the hailstone sequence for a number.
Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1
Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.
(But don't show the actual sequence!)
See also
xkcd (humourous).
The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).
The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).
|
#MUMPS
|
MUMPS
|
hailstone(n) ;
If n=1 Quit n
If n#2 Quit n_" "_$$hailstone(3*n+1)
Quit n_" "_$$hailstone(n\2)
Set x=$$hailstone(27) Write !,$Length(x," ")," terms in ",x,!
112 terms in 27 82 41 124 62 31 94 47 142 71 214 107 322 161 484 242 121 364 182 91 274 137 412 206 103 310 155 466 233 700 350 175 526 263 790 395 1186 593 1780 890 445 1336 668 334 167 502 251 754 377 1132 566 283 850 425 1276 638 319 958 479 1438 719 2158 1079 3238 1619 4858 2429 7288 3644 1822 911 2734 1367 4102 2051 6154 3077 9232 4616 2308 1154 577 1732 866 433 1300 650 325 976 488 244 122 61 184 92 46 23 70 35 106 53 160 80 40 20 10 5 16 8 4 2 1
|
http://rosettacode.org/wiki/Happy_numbers
|
Happy numbers
|
From Wikipedia, the free encyclopedia:
A happy number is defined by the following process:
Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.
Those numbers for which this process end in 1 are happy numbers,
while those numbers that do not end in 1 are unhappy numbers.
Task
Find and print the first 8 happy numbers.
Display an example of your output here on this page.
See also
The OEIS entry: The happy numbers: A007770
The OEIS entry: The unhappy numbers; A031177
|
#VBA
|
VBA
|
Option Explicit
Sub Test_Happy()
Dim i&, Cpt&
For i = 1 To 100
If Is_Happy_Number(i) Then
Debug.Print "Is Happy : " & i
Cpt = Cpt + 1
If Cpt = 8 Then Exit For
End If
Next
End Sub
Public Function Is_Happy_Number(ByVal N As Long) As Boolean
Dim i&, Number$, Cpt&
Is_Happy_Number = False 'default value
Do
Cpt = Cpt + 1 'Count Loops
Number = CStr(N) 'conversion Long To String to be able to use Len() function
N = 0
For i = 1 To Len(Number)
N = N + CInt(Mid(Number, i, 1)) ^ 2
Next i
'If Not N = 1 after 50 Loop ==> Number Is Not Happy
If Cpt = 50 Then Exit Function
Loop Until N = 1
Is_Happy_Number = True
End Function
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#M2000_Interpreter
|
M2000 Interpreter
|
Print "Hello World!" \\ printing on columns, in various ways defined by last $() for specific layer
Print $(4),"Hello World!" \\ proportional printing using columns, expanded to a number of columns as the length of string indicates.
Report "Hello World!" \\ proportional printing with word wrap, for text, can apply justification and rendering a range of text lines
|
http://rosettacode.org/wiki/Generic_swap
|
Generic swap
|
Task
Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types.
If your solution language is statically typed please describe the way your language provides genericity.
If variables are typed in the given language, it is permissible that the two variables be constrained to having a mutually compatible type, such that each is permitted to hold the value previously stored in the other without a type violation.
That is to say, solutions do not have to be capable of exchanging, say, a string and integer value, if the underlying storage locations are not attributed with types that permit such an exchange.
Generic swap is a task which brings together a few separate issues in programming language semantics.
Dynamically typed languages deal with values in a generic way quite readily, but do not necessarily make it easy to write a function to destructively swap two variables, because this requires indirection upon storage places or upon the syntax designating storage places.
Functional languages, whether static or dynamic, do not necessarily allow a destructive operation such as swapping two variables regardless of their generic capabilities.
Some static languages have difficulties with generic programming due to a lack of support for (Parametric Polymorphism).
Do your best!
|
#M4
|
M4
|
define(`def2', `define(`$1',`$2')define(`$3',`$4')')dnl
define(`swap', `def2(`$1',defn(`$2'),`$2',defn(`$1'))')dnl
dnl
define(`a',`x')dnl
define(`b',`y')dnl
a b
swap(`a',`b')
a b
|
http://rosettacode.org/wiki/Greatest_element_of_a_list
|
Greatest element of a list
|
Task
Create a function that returns the maximum value in a provided set of values,
where the number of values may not be known until run-time.
|
#ooRexx
|
ooRexx
|
-- routine that will work with any ordered collection or sets and bags containing numbers.
::routine listMax
use arg list
items list~makearray -- since we're dealing with different collection types, reduce to an array
if items~isEmpty then return .nil -- return a failure indicator. could also raise an error, if desired
largest = items[1]
-- note, this method does call max one extra time. This could also use the
-- do i = 2 to items~size to avoid this
do item over items
largest = max(item, largest)
end
return largest
|
http://rosettacode.org/wiki/Greatest_common_divisor
|
Greatest common divisor
|
Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related task
least common multiple.
See also
MathWorld entry: greatest common divisor.
Wikipedia entry: greatest common divisor.
|
#M2000_Interpreter
|
M2000 Interpreter
|
gcd=lambda (u as long, v as long) -> {
=if(v=0&->abs(u), lambda(v, u mod v))
}
gcd_Iterative= lambda (m as long, n as long) -> {
while m {
let old_m = m
m = n mod m
n = old_m
}
=abs(n)
}
Module CheckGCD (f){
Print f(49865, 69811)=9973
Def ExpType$(x)=Type$(x)
Print ExpType$(f(49865, 69811))="Long"
}
CheckGCD gcd
CheckGCD gcd_Iterative
|
http://rosettacode.org/wiki/Hailstone_sequence
|
Hailstone sequence
|
The Hailstone sequence of numbers can be generated from a starting positive integer, n by:
If n is 1 then the sequence ends.
If n is even then the next n of the sequence = n/2
If n is odd then the next n of the sequence = (3 * n) + 1
The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates.
This sequence was named by Lothar Collatz in 1937 (or possibly in 1939), and is also known as (the):
hailstone sequence, hailstone numbers
3x + 2 mapping, 3n + 1 problem
Collatz sequence
Hasse's algorithm
Kakutani's problem
Syracuse algorithm, Syracuse problem
Thwaites conjecture
Ulam's problem
The hailstone sequence is also known as hailstone numbers (because the values are usually subject to multiple descents and ascents like hailstones in a cloud).
Task
Create a routine to generate the hailstone sequence for a number.
Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1
Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.
(But don't show the actual sequence!)
See also
xkcd (humourous).
The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).
The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).
|
#Nanoquery
|
Nanoquery
|
def hailstone(n)
seq = list()
while (n > 1)
append seq n
if (n % 2)=0
n = int(n / 2)
else
n = int((3 * n) + 1)
end
end
append seq n
return seq
end
h = hailstone(27)
println "hailstone(27)"
println "total elements: " + len(hailstone(27))
print h[0] + ", " + h[1] + ", " + h[2] + ", " + h[3] + ", ..., "
println h[-4] + ", " + h[-3] + ", " + h[-2] + ", " + h[-1]
max = 0
maxLoc = 0
for i in range(1,99999)
result = len(hailstone(i))
if (result > max)
max = result
maxLoc = i
end
end
print "\nThe number less than 100,000 with the longest sequence is "
println maxLoc + " with a length of " + max
|
http://rosettacode.org/wiki/Happy_numbers
|
Happy numbers
|
From Wikipedia, the free encyclopedia:
A happy number is defined by the following process:
Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.
Those numbers for which this process end in 1 are happy numbers,
while those numbers that do not end in 1 are unhappy numbers.
Task
Find and print the first 8 happy numbers.
Display an example of your output here on this page.
See also
The OEIS entry: The happy numbers: A007770
The OEIS entry: The unhappy numbers; A031177
|
#VBScript
|
VBScript
|
count = 0
firsteigth=""
For i = 1 To 100
If IsHappy(CInt(i)) Then
firsteight = firsteight & i & ","
count = count + 1
End If
If count = 8 Then
Exit For
End If
Next
WScript.Echo firsteight
Function IsHappy(n)
IsHappy = False
m = 0
Do Until m = 60
sum = 0
For j = 1 To Len(n)
sum = sum + (Mid(n,j,1))^2
Next
If sum = 1 Then
IsHappy = True
Exit Do
Else
n = sum
m = m + 1
End If
Loop
End Function
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#M4
|
M4
|
`Hello world!'
|
http://rosettacode.org/wiki/Generic_swap
|
Generic swap
|
Task
Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types.
If your solution language is statically typed please describe the way your language provides genericity.
If variables are typed in the given language, it is permissible that the two variables be constrained to having a mutually compatible type, such that each is permitted to hold the value previously stored in the other without a type violation.
That is to say, solutions do not have to be capable of exchanging, say, a string and integer value, if the underlying storage locations are not attributed with types that permit such an exchange.
Generic swap is a task which brings together a few separate issues in programming language semantics.
Dynamically typed languages deal with values in a generic way quite readily, but do not necessarily make it easy to write a function to destructively swap two variables, because this requires indirection upon storage places or upon the syntax designating storage places.
Functional languages, whether static or dynamic, do not necessarily allow a destructive operation such as swapping two variables regardless of their generic capabilities.
Some static languages have difficulties with generic programming due to a lack of support for (Parametric Polymorphism).
Do your best!
|
#Maple
|
Maple
|
> a, b := 2, "foo":
> a;
2
> b;
"foo"
> a, b := b, a: # SWAP
> a;
"foo"
> b;
2
|
http://rosettacode.org/wiki/Greatest_element_of_a_list
|
Greatest element of a list
|
Task
Create a function that returns the maximum value in a provided set of values,
where the number of values may not be known until run-time.
|
#OxygenBasic
|
OxygenBasic
|
'Works on any list with element types which support '>' comparisons
macro max any(R, A, N, i)
============================
scope
indexbase 1
int i
R=A(1)
for i=2 to N
if A(i)>R
R=A(i)
endif
next
end scope
end macro
'DEMO
=====
redim double d(100)
d={ 1.1, 1.2, 5.5, -0.1, -12.0 }
double m=max(d,5)
print "greatest element of d(): " m '5.5
|
http://rosettacode.org/wiki/Greatest_common_divisor
|
Greatest common divisor
|
Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related task
least common multiple.
See also
MathWorld entry: greatest common divisor.
Wikipedia entry: greatest common divisor.
|
#m4
|
m4
|
divert(-1)
define(`gcd',
`ifelse(eval(`0 <= (' $1 `)'),`0',`gcd(eval(`-(' $1 `)'),eval(`(' $2 `)'))',
eval(`0 <= (' $2 `)'),`0',`gcd(eval(`(' $1 `)'),eval(`-(' $2 `)'))',
eval(`(' $1 `) == 0'),`0',`gcd(eval(`(' $2 `) % (' $1 `)'),eval(`(' $1 `)'))',
eval(`(' $2 `)'))')
divert`'dnl
dnl
gcd(0, 0) = 0
gcd(24140, 40902) = 34
gcd(-24140, -40902) = 34
gcd(-40902, 24140) = 34
gcd(40902, -24140) = 34
|
http://rosettacode.org/wiki/Hailstone_sequence
|
Hailstone sequence
|
The Hailstone sequence of numbers can be generated from a starting positive integer, n by:
If n is 1 then the sequence ends.
If n is even then the next n of the sequence = n/2
If n is odd then the next n of the sequence = (3 * n) + 1
The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates.
This sequence was named by Lothar Collatz in 1937 (or possibly in 1939), and is also known as (the):
hailstone sequence, hailstone numbers
3x + 2 mapping, 3n + 1 problem
Collatz sequence
Hasse's algorithm
Kakutani's problem
Syracuse algorithm, Syracuse problem
Thwaites conjecture
Ulam's problem
The hailstone sequence is also known as hailstone numbers (because the values are usually subject to multiple descents and ascents like hailstones in a cloud).
Task
Create a routine to generate the hailstone sequence for a number.
Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1
Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.
(But don't show the actual sequence!)
See also
xkcd (humourous).
The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).
The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).
|
#NetRexx
|
NetRexx
|
/* NetRexx */
options replace format comments java crossref savelog symbols binary
do
start = 27
hs = hailstone(start)
hsCount = hs.words
say 'The number' start 'has a hailstone sequence comprising' hsCount 'elements'
say ' its first four elements are:' hs.subword(1, 4)
say ' and last four elements are:' hs.subword(hsCount - 3)
hsMax = 0
hsCountMax = 0
llimit = 100000
loop x_ = 1 to llimit - 1
hs = hailstone(x_)
hsCount = hs.words
if hsCount > hsCountMax then do
hsMax = x_
hsCountMax = hsCount
end
end x_
say 'The number' hsMax 'has the longest hailstone sequence in the range 1 to' llimit - 1 'with a sequence length of' hsCountMax
catch ex = Exception
ex.printStackTrace
end
return
method hailstone(hn = long) public static returns Rexx signals IllegalArgumentException
hs = Rexx('')
if hn <= 0 then signal IllegalArgumentException('Invalid start point. Must be a positive integer greater than 0')
loop label n_ while hn > 1
hs = hs' 'hn
if hn // 2 \= 0 then hn = hn * 3 + 1
else hn = hn % 2
end n_
hs = hs' 'hn
return hs.strip
|
http://rosettacode.org/wiki/Happy_numbers
|
Happy numbers
|
From Wikipedia, the free encyclopedia:
A happy number is defined by the following process:
Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.
Those numbers for which this process end in 1 are happy numbers,
while those numbers that do not end in 1 are unhappy numbers.
Task
Find and print the first 8 happy numbers.
Display an example of your output here on this page.
See also
The OEIS entry: The happy numbers: A007770
The OEIS entry: The unhappy numbers; A031177
|
#Visual_Basic_.NET
|
Visual Basic .NET
|
Module HappyNumbers
Sub Main()
Dim n As Integer = 1
Dim found As Integer = 0
Do Until found = 8
If IsHappy(n) Then
found += 1
Console.WriteLine("{0}: {1}", found, n)
End If
n += 1
Loop
Console.ReadLine()
End Sub
Private Function IsHappy(ByVal n As Integer)
Dim cache As New List(Of Long)()
Do Until n = 1
cache.Add(n)
n = Aggregate c In n.ToString() _
Into Total = Sum(Int32.Parse(c) ^ 2)
If cache.Contains(n) Then Return False
Loop
Return True
End Function
End Module
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#MACRO-10
|
MACRO-10
|
TITLE HELLO
COMMENT !
Hello-World program, PDP-10 assembly language, written by kjx, 2022.
Assembler: MACRO-10 Operating system: TOPS-20
!
SEARCH MONSYM ;Get symbolic names for system-calls.
GO:: RESET% ;System call: Initialize process.
HRROI 1,[ASCIZ /Hello World!/] ;Put pointer to string into register 1.
PSOUT% ;System call: Print string.
HALTF% ;System call: Halt program.
JRST GO ;Unconditional jump to GO (in case the
;user uses the CONTINUE-command while this
;program is still loaded).
END GO
|
http://rosettacode.org/wiki/Generic_swap
|
Generic swap
|
Task
Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types.
If your solution language is statically typed please describe the way your language provides genericity.
If variables are typed in the given language, it is permissible that the two variables be constrained to having a mutually compatible type, such that each is permitted to hold the value previously stored in the other without a type violation.
That is to say, solutions do not have to be capable of exchanging, say, a string and integer value, if the underlying storage locations are not attributed with types that permit such an exchange.
Generic swap is a task which brings together a few separate issues in programming language semantics.
Dynamically typed languages deal with values in a generic way quite readily, but do not necessarily make it easy to write a function to destructively swap two variables, because this requires indirection upon storage places or upon the syntax designating storage places.
Functional languages, whether static or dynamic, do not necessarily allow a destructive operation such as swapping two variables regardless of their generic capabilities.
Some static languages have difficulties with generic programming due to a lack of support for (Parametric Polymorphism).
Do your best!
|
#Mathematica_.2F_Wolfram_Language
|
Mathematica / Wolfram Language
|
swap[a_, b_] := {a, b} = {b, a}
SetAttributes[swap, HoldAll]
|
http://rosettacode.org/wiki/Greatest_element_of_a_list
|
Greatest element of a list
|
Task
Create a function that returns the maximum value in a provided set of values,
where the number of values may not be known until run-time.
|
#Oz
|
Oz
|
declare
fun {Maximum X|Xr} %% pattern-match on argument to make sure the list is not empty
{FoldL Xr Value.max X} %% fold the binary function Value.max over the list
end
in
{Show {Maximum [1 2 3 4 3]}}
|
http://rosettacode.org/wiki/Greatest_common_divisor
|
Greatest common divisor
|
Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related task
least common multiple.
See also
MathWorld entry: greatest common divisor.
Wikipedia entry: greatest common divisor.
|
#Maple
|
Maple
|
igcd( a, b )
|
http://rosettacode.org/wiki/Hailstone_sequence
|
Hailstone sequence
|
The Hailstone sequence of numbers can be generated from a starting positive integer, n by:
If n is 1 then the sequence ends.
If n is even then the next n of the sequence = n/2
If n is odd then the next n of the sequence = (3 * n) + 1
The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates.
This sequence was named by Lothar Collatz in 1937 (or possibly in 1939), and is also known as (the):
hailstone sequence, hailstone numbers
3x + 2 mapping, 3n + 1 problem
Collatz sequence
Hasse's algorithm
Kakutani's problem
Syracuse algorithm, Syracuse problem
Thwaites conjecture
Ulam's problem
The hailstone sequence is also known as hailstone numbers (because the values are usually subject to multiple descents and ascents like hailstones in a cloud).
Task
Create a routine to generate the hailstone sequence for a number.
Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1
Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.
(But don't show the actual sequence!)
See also
xkcd (humourous).
The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).
The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).
|
#Nim
|
Nim
|
proc hailstone(n: int): seq[int] =
result = @[n]
var n = n
while n > 1:
if (n and 1) == 1:
n = 3 * n + 1
else:
n = n div 2
result.add n
when isMainModule:
import strformat, strutils
let h = hailstone(27)
echo &"Hailstone sequence for number 27 has {h.len} elements."
let first = h[0..3].join(", ")
let last = h[^4..^1].join(", ")
echo &"This sequence begins with {first} and ends with {last}."
var m, mi = 0
for i in 1..<100_000:
let n = hailstone(i).len
if n > m:
m = n
mi = i
echo &"\nFor numbers < 100_000, maximum length {m} was found for Hailstone({mi})."
|
http://rosettacode.org/wiki/Happy_numbers
|
Happy numbers
|
From Wikipedia, the free encyclopedia:
A happy number is defined by the following process:
Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.
Those numbers for which this process end in 1 are happy numbers,
while those numbers that do not end in 1 are unhappy numbers.
Task
Find and print the first 8 happy numbers.
Display an example of your output here on this page.
See also
The OEIS entry: The happy numbers: A007770
The OEIS entry: The unhappy numbers; A031177
|
#Vlang
|
Vlang
|
fn happy(h int) bool {
mut m := map[int]bool{}
mut n := h
for n > 1 {
m[n] = true
mut x := 0
for x, n = n, 0; x > 0; x /= 10 {
d := x % 10
n += d * d
}
if m[n] {
return false
}
}
return true
}
fn main() {
for found, n := 0, 1; found < 8; n++ {
if happy(n) {
print("$n ")
found++
}
}
println('')
}
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#MACRO-11
|
MACRO-11
|
;
; TEXT BASED HELLO WORLD
; WRITTEN BY: BILL GUNSHANNON
;
.MCALL .PRINT .EXIT
.RADIX 10
MESG1: .ASCII " "
.ASCII " HELLO WORLD "
.EVEN
START:
.PRINT #MESG1
DONE:
; CLEAN UP AND GO BACK TO KMON
.EXIT
.END START
|
http://rosettacode.org/wiki/Generic_swap
|
Generic swap
|
Task
Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types.
If your solution language is statically typed please describe the way your language provides genericity.
If variables are typed in the given language, it is permissible that the two variables be constrained to having a mutually compatible type, such that each is permitted to hold the value previously stored in the other without a type violation.
That is to say, solutions do not have to be capable of exchanging, say, a string and integer value, if the underlying storage locations are not attributed with types that permit such an exchange.
Generic swap is a task which brings together a few separate issues in programming language semantics.
Dynamically typed languages deal with values in a generic way quite readily, but do not necessarily make it easy to write a function to destructively swap two variables, because this requires indirection upon storage places or upon the syntax designating storage places.
Functional languages, whether static or dynamic, do not necessarily allow a destructive operation such as swapping two variables regardless of their generic capabilities.
Some static languages have difficulties with generic programming due to a lack of support for (Parametric Polymorphism).
Do your best!
|
#MATLAB_.2F_Octave
|
MATLAB / Octave
|
>> a = [30 40 50 60 70]
a =
30 40 50 60 70
>> a([1 3]) = a([3 1]) %Single swap
a =
50 40 30 60 70
>> a([1 2 4 3]) = a([2 3 1 4]) %Multiple swap, a.k.a permutation.
a =
40 30 60 50 70
|
http://rosettacode.org/wiki/Greatest_element_of_a_list
|
Greatest element of a list
|
Task
Create a function that returns the maximum value in a provided set of values,
where the number of values may not be known until run-time.
|
#PARI.2FGP
|
PARI/GP
|
vecmax(v)
|
http://rosettacode.org/wiki/Greatest_common_divisor
|
Greatest common divisor
|
Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related task
least common multiple.
See also
MathWorld entry: greatest common divisor.
Wikipedia entry: greatest common divisor.
|
#Mathematica_.2F_Wolfram_Language
|
Mathematica / Wolfram Language
|
GCD[a, b]
|
http://rosettacode.org/wiki/Hailstone_sequence
|
Hailstone sequence
|
The Hailstone sequence of numbers can be generated from a starting positive integer, n by:
If n is 1 then the sequence ends.
If n is even then the next n of the sequence = n/2
If n is odd then the next n of the sequence = (3 * n) + 1
The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates.
This sequence was named by Lothar Collatz in 1937 (or possibly in 1939), and is also known as (the):
hailstone sequence, hailstone numbers
3x + 2 mapping, 3n + 1 problem
Collatz sequence
Hasse's algorithm
Kakutani's problem
Syracuse algorithm, Syracuse problem
Thwaites conjecture
Ulam's problem
The hailstone sequence is also known as hailstone numbers (because the values are usually subject to multiple descents and ascents like hailstones in a cloud).
Task
Create a routine to generate the hailstone sequence for a number.
Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1
Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.
(But don't show the actual sequence!)
See also
xkcd (humourous).
The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).
The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).
|
#Oberon-2
|
Oberon-2
|
MODULE hailst;
IMPORT Out;
CONST maxCard = MAX (INTEGER) DIV 3;
List = 1;
Count = 2;
Max = 3;
VAR a : INTEGER;
PROCEDURE HailStone (start, type : INTEGER) : INTEGER;
VAR n, max, count : INTEGER;
BEGIN
count := 1;
n := start;
max := n;
LOOP
IF type = List THEN
Out.Int (n, 12);
IF count MOD 6 = 0 THEN Out.Ln END
END;
IF n = 1 THEN EXIT END;
IF ODD (n) THEN
IF n < maxCard THEN
n := 3 * n + 1;
IF n > max THEN max := n END
ELSE
Out.String ("Exceeding max value for type INTEGER at: ");
Out.String (" n = "); Out.Int (start, 12);
Out.String (" , count = "); Out.Int (count, 12);
Out.String (" and intermediate value ");
Out.Int (n, 1);
Out.String (". Aborting.");
Out.Ln;
HALT (2)
END
ELSE
n := n DIV 2
END;
INC (count)
END;
IF type = Max THEN RETURN max ELSE RETURN count END
END HailStone;
PROCEDURE FindMax (num : INTEGER);
VAR val, maxCount, maxVal, cnt : INTEGER;
BEGIN
maxCount := 0;
maxVal := 0;
FOR val := 2 TO num DO
cnt := HailStone (val, Count);
IF cnt > maxCount THEN
maxVal := val;
maxCount := cnt
END
END;
Out.String ("Longest sequence below "); Out.Int (num, 1);
Out.String (" is "); Out.Int (HailStone (maxVal, Count), 1);
Out.String (" for n = "); Out.Int (maxVal, 1);
Out.String (" with an intermediate maximum of ");
Out.Int (HailStone (maxVal, Max), 1);
Out.Ln
END FindMax;
BEGIN
a := HailStone (27, List);
Out.Ln;
Out.String ("Iterations total = "); Out.Int (HailStone (27, Count), 12);
Out.String (" max value = "); Out.Int (HailStone (27, Max) , 12);
Out.Ln;
FindMax (1000000);
Out.String ("Done.");
Out.Ln
END hailst.
|
http://rosettacode.org/wiki/Happy_numbers
|
Happy numbers
|
From Wikipedia, the free encyclopedia:
A happy number is defined by the following process:
Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.
Those numbers for which this process end in 1 are happy numbers,
while those numbers that do not end in 1 are unhappy numbers.
Task
Find and print the first 8 happy numbers.
Display an example of your output here on this page.
See also
The OEIS entry: The happy numbers: A007770
The OEIS entry: The unhappy numbers; A031177
|
#Wren
|
Wren
|
var happy = Fn.new { |n|
var m = {}
while (n > 1) {
m[n] = true
var x = n
n = 0
while (x > 0) {
var d = x % 10
n = n + d*d
x = (x/10).floor
}
if (m[n] == true) return false // m[n] will be null if 'n' is not a key
}
return true
}
var found = 0
var n = 1
while (found < 8) {
if (happy.call(n)) {
System.write("%(n) ")
found = found + 1
}
n = n + 1
}
System.print()
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#Maclisp
|
Maclisp
|
(format t "Hello world!~%")
|
http://rosettacode.org/wiki/Generic_swap
|
Generic swap
|
Task
Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types.
If your solution language is statically typed please describe the way your language provides genericity.
If variables are typed in the given language, it is permissible that the two variables be constrained to having a mutually compatible type, such that each is permitted to hold the value previously stored in the other without a type violation.
That is to say, solutions do not have to be capable of exchanging, say, a string and integer value, if the underlying storage locations are not attributed with types that permit such an exchange.
Generic swap is a task which brings together a few separate issues in programming language semantics.
Dynamically typed languages deal with values in a generic way quite readily, but do not necessarily make it easy to write a function to destructively swap two variables, because this requires indirection upon storage places or upon the syntax designating storage places.
Functional languages, whether static or dynamic, do not necessarily allow a destructive operation such as swapping two variables regardless of their generic capabilities.
Some static languages have difficulties with generic programming due to a lack of support for (Parametric Polymorphism).
Do your best!
|
#Maxima
|
Maxima
|
a: 10$
b: foo$
/* A simple way to swap values */
[a, b]: [b, a]$
a; /* foo */
b; /* 10 */
/* A macro to hide this */
swap(x, y) ::= buildq([x, y], ([x, y]: [y, x], 'done))$
swap(a, b)$
a; /* 10 */
b; /* foo */
|
http://rosettacode.org/wiki/Greatest_element_of_a_list
|
Greatest element of a list
|
Task
Create a function that returns the maximum value in a provided set of values,
where the number of values may not be known until run-time.
|
#Pascal
|
Pascal
|
program GElemLIst;
{$IFNDEF FPC}
{$Apptype Console}
{$else}
{$Mode Delphi}
{$ENDIF}
uses
sysutils;
const
MaxCnt = 1000000;
type
tMaxIntPos= record
mpMax,
mpPos : integer;
end;
tMaxfltPos= record
mpMax : double;
mpPos : integer;
end;
function FindMaxInt(const ia: array of integer):tMaxIntPos;
//delivers the highest Element and position of integer array
var
i : NativeInt;
tmp,max,ps: integer;
Begin
max := -MaxInt-1;
ps := -1;
//i = index of last Element
i := length(ia)-1;
IF i>=0 then Begin
max := ia[i];
ps := i;
dec(i);
while i> 0 do begin
tmp := ia[i];
IF max< tmp then begin
max := tmp;
ps := i;
end;
dec(i);
end;
end;
result.mpMax := Max;
result.mpPos := ps;
end;
function FindMaxflt(const ia: array of double):tMaxfltPos;
//delivers the highest Element and position of double array
var
i,
ps: NativeInt;
max : double;
tmp : ^double;//for 32-bit version runs faster
Begin
max := -MaxInt-1;
ps := -1;
//i = index of last Element
i := length(ia)-1;
IF i>=0 then Begin
max := ia[i];
ps := i;
dec(i);
tmp := @ia[i];
while i> 0 do begin
IF tmp^>max then begin
max := tmp^;
ps := i;
end;
dec(i);
dec(tmp);
end;
end;
result.mpMax := Max;
result.mpPos := ps;
end;
var
IntArr : array of integer;
fltArr : array of double;
ErgInt : tMaxINtPos;
ErgFlt : tMaxfltPos;
i: NativeInt;
begin
randomize;
setlength(fltArr,MaxCnt); //filled with 0
setlength(IntArr,MaxCnt); //filled with 0.0
For i := High(fltArr) downto 0 do
fltArr[i] := MaxCnt*random();
For i := High(IntArr) downto 0 do
IntArr[i] := round(fltArr[i]);
ErgInt := FindMaxInt(IntArr);
writeln('FindMaxInt ',ErgInt.mpMax,' @ ',ErgInt.mpPos);
Ergflt := FindMaxflt(fltArr);
writeln('FindMaxFlt ',Ergflt.mpMax:0:4,' @ ',Ergflt.mpPos);
end.
|
http://rosettacode.org/wiki/Greatest_common_divisor
|
Greatest common divisor
|
Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related task
least common multiple.
See also
MathWorld entry: greatest common divisor.
Wikipedia entry: greatest common divisor.
|
#MATLAB
|
MATLAB
|
function [gcdValue] = greatestcommondivisor(integer1, integer2)
gcdValue = gcd(integer1, integer2);
|
http://rosettacode.org/wiki/Hailstone_sequence
|
Hailstone sequence
|
The Hailstone sequence of numbers can be generated from a starting positive integer, n by:
If n is 1 then the sequence ends.
If n is even then the next n of the sequence = n/2
If n is odd then the next n of the sequence = (3 * n) + 1
The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates.
This sequence was named by Lothar Collatz in 1937 (or possibly in 1939), and is also known as (the):
hailstone sequence, hailstone numbers
3x + 2 mapping, 3n + 1 problem
Collatz sequence
Hasse's algorithm
Kakutani's problem
Syracuse algorithm, Syracuse problem
Thwaites conjecture
Ulam's problem
The hailstone sequence is also known as hailstone numbers (because the values are usually subject to multiple descents and ascents like hailstones in a cloud).
Task
Create a routine to generate the hailstone sequence for a number.
Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1
Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.
(But don't show the actual sequence!)
See also
xkcd (humourous).
The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).
The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).
|
#OCaml
|
OCaml
|
#load "nums.cma";;
open Num;;
(* generate Hailstone sequence *)
let hailstone n =
let one = Int 1
and two = Int 2
and three = Int 3 in
let rec g s x =
if x =/ one
then x::s
else g (x::s) (if mod_num x two =/ one
then three */ x +/ one
else x // two)
in
g [] (Int n)
;;
(* compute only sequence length *)
let haillen n =
let one = Int 1
and two = Int 2
and three = Int 3 in
let rec g s x =
if x =/ one
then s+1
else g (s+1) (if mod_num x two =/ one
then three */ x +/ one
else x // two)
in
g 0 (Int n)
;;
(* max length for starting values in 1..n *)
let hailmax =
let rec g idx len = function
| 0 -> (idx, len)
| i ->
let a = haillen i in
if a > len
then g i a (i-1)
else g idx len (i-1)
in
g 0 0
;;
hailmax 100000 ;;
(* - : int * int = (77031, 351) *)
List.rev_map string_of_num (hailstone 27) ;;
(* - : string list =
["27"; "82"; "41"; "124"; "62"; "31"; "94"; "47"; "142"; "71"; "214"; "107";
"322"; "161"; "484"; "242"; "121"; "364"; "182"; "91"; "274"; "137"; "412";
"206"; "103"; "310"; "155"; "466"; "233"; "700"; "350"; "175"; "526"; "263";
"790"; "395"; "1186"; "593"; "1780"; "890"; "445"; "1336"; "668"; "334";
"167"; "502"; "251"; "754"; "377"; "1132"; "566"; "283"; "850"; "425";
"1276"; "638"; "319"; "958"; "479"; "1438"; "719"; "2158"; "1079"; "3238";
"1619"; "4858"; "2429"; "7288"; "3644"; "1822"; "911"; "2734"; "1367";
"4102"; "2051"; "6154"; "3077"; "9232"; "4616"; "2308"; "1154"; "577";
"1732"; "866"; "433"; "1300"; "650"; "325"; "976"; "488"; "244"; "122";
"61"; "184"; "92"; "46"; "23"; "70"; "35"; "106"; "53"; "160"; "80"; "40";
"20"; "10"; "5"; "16"; "8"; "4"; "2"; "1"] *)
|
http://rosettacode.org/wiki/Happy_numbers
|
Happy numbers
|
From Wikipedia, the free encyclopedia:
A happy number is defined by the following process:
Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.
Those numbers for which this process end in 1 are happy numbers,
while those numbers that do not end in 1 are unhappy numbers.
Task
Find and print the first 8 happy numbers.
Display an example of your output here on this page.
See also
The OEIS entry: The happy numbers: A007770
The OEIS entry: The unhappy numbers; A031177
|
#XPL0
|
XPL0
|
int List(810); \list of numbers in a cycle
int Inx; \index for List
include c:\cxpl\codes;
func HadNum(N); \Return 'true' if number N is in the List
int N;
int I;
[for I:= 0 to Inx-1 do
if N = List(I) then return true;
return false;
]; \HadNum
func SqDigits(N); \Return the sum of the squares of the digits of N
int N;
int S, D;
[S:= 0;
while N do
[N:= N/10;
D:= rem(0);
S:= S + D*D;
];
return S;
]; \SqDigits
int N0, N, C;
[N0:= 0; \starting number
C:= 0; \initialize happy (starting) number counter
repeat N:= N0;
Inx:= 0; \reset List index
loop [N:= SqDigits(N);
if N = 1 then \happy number
[IntOut(0, N0); CrLf(0);
C:= C+1;
quit;
];
if HadNum(N) then quit; \if unhappy number then quit
List(Inx):= N; \if neither, add it to the List
Inx:= Inx+1; \ and continue the cycle
];
N0:= N0+1; \next starting number
until C=8; \done when 8 happy numbers have been found
]
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#MAD
|
MAD
|
VECTOR VALUES HELLO = $11HHELLO WORLD*$
PRINT FORMAT HELLO
END OF PROGRAM
|
http://rosettacode.org/wiki/Generic_swap
|
Generic swap
|
Task
Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types.
If your solution language is statically typed please describe the way your language provides genericity.
If variables are typed in the given language, it is permissible that the two variables be constrained to having a mutually compatible type, such that each is permitted to hold the value previously stored in the other without a type violation.
That is to say, solutions do not have to be capable of exchanging, say, a string and integer value, if the underlying storage locations are not attributed with types that permit such an exchange.
Generic swap is a task which brings together a few separate issues in programming language semantics.
Dynamically typed languages deal with values in a generic way quite readily, but do not necessarily make it easy to write a function to destructively swap two variables, because this requires indirection upon storage places or upon the syntax designating storage places.
Functional languages, whether static or dynamic, do not necessarily allow a destructive operation such as swapping two variables regardless of their generic capabilities.
Some static languages have difficulties with generic programming due to a lack of support for (Parametric Polymorphism).
Do your best!
|
#MAXScript
|
MAXScript
|
swap a b
|
http://rosettacode.org/wiki/Greatest_element_of_a_list
|
Greatest element of a list
|
Task
Create a function that returns the maximum value in a provided set of values,
where the number of values may not be known until run-time.
|
#Perl
|
Perl
|
sub max {
my $max = shift;
for (@_) { $max = $_ if $_ > $max }
return $max;
}
|
http://rosettacode.org/wiki/Greatest_common_divisor
|
Greatest common divisor
|
Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related task
least common multiple.
See also
MathWorld entry: greatest common divisor.
Wikipedia entry: greatest common divisor.
|
#Maxima
|
Maxima
|
/* There is a function gcd(a, b) in Maxima, but one can rewrite it */
gcd2(a, b) := block([a: abs(a), b: abs(b)], while b # 0 do [a, b]: [b, mod(a, b)], a)$
/* both will return 2^97 * 3^48 */
gcd(100!, 6^100), factor;
gcd2(100!, 6^100), factor;
|
http://rosettacode.org/wiki/Hailstone_sequence
|
Hailstone sequence
|
The Hailstone sequence of numbers can be generated from a starting positive integer, n by:
If n is 1 then the sequence ends.
If n is even then the next n of the sequence = n/2
If n is odd then the next n of the sequence = (3 * n) + 1
The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates.
This sequence was named by Lothar Collatz in 1937 (or possibly in 1939), and is also known as (the):
hailstone sequence, hailstone numbers
3x + 2 mapping, 3n + 1 problem
Collatz sequence
Hasse's algorithm
Kakutani's problem
Syracuse algorithm, Syracuse problem
Thwaites conjecture
Ulam's problem
The hailstone sequence is also known as hailstone numbers (because the values are usually subject to multiple descents and ascents like hailstones in a cloud).
Task
Create a routine to generate the hailstone sequence for a number.
Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1
Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.
(But don't show the actual sequence!)
See also
xkcd (humourous).
The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).
The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).
|
#Oforth
|
Oforth
|
: hailstone // n -- [n]
| l |
ListBuffer new ->l
while(dup 1 <>) [ dup l add dup isEven ifTrue: [ 2 / ] else: [ 3 * 1+ ] ]
l add l dup freeze ;
hailstone(27) dup size println dup left(4) println right(4) println
100000 seq map(#[ dup hailstone size swap Pair new ]) reduce(#maxKey) println
|
http://rosettacode.org/wiki/Happy_numbers
|
Happy numbers
|
From Wikipedia, the free encyclopedia:
A happy number is defined by the following process:
Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.
Those numbers for which this process end in 1 are happy numbers,
while those numbers that do not end in 1 are unhappy numbers.
Task
Find and print the first 8 happy numbers.
Display an example of your output here on this page.
See also
The OEIS entry: The happy numbers: A007770
The OEIS entry: The unhappy numbers; A031177
|
#Zig
|
Zig
|
const std = @import("std");
const stdout = std.io.getStdOut().outStream();
pub fn main() !void {
try stdout.print("The first 8 happy numbers are: ", .{});
var n: u32 = 1;
var c: u4 = 0;
while (c < 8) {
if (isHappy(n)) {
c += 1;
try stdout.print("{} ", .{n});
}
n += 1;
}
try stdout.print("\n", .{});
}
fn isHappy(n: u32) bool {
var t = n;
var h = sumsq(n);
while (t != h) {
t = sumsq(t);
h = sumsq(sumsq(h));
}
return t == 1;
}
fn sumsq(n0: u32) u32 {
var s: u32 = 0;
var n = n0;
while (n > 0) : (n /= 10) {
const m = n % 10;
s += m * m;
}
return s;
}
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#make
|
make
|
all:
$(info Hello world!)
|
http://rosettacode.org/wiki/Generic_swap
|
Generic swap
|
Task
Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types.
If your solution language is statically typed please describe the way your language provides genericity.
If variables are typed in the given language, it is permissible that the two variables be constrained to having a mutually compatible type, such that each is permitted to hold the value previously stored in the other without a type violation.
That is to say, solutions do not have to be capable of exchanging, say, a string and integer value, if the underlying storage locations are not attributed with types that permit such an exchange.
Generic swap is a task which brings together a few separate issues in programming language semantics.
Dynamically typed languages deal with values in a generic way quite readily, but do not necessarily make it easy to write a function to destructively swap two variables, because this requires indirection upon storage places or upon the syntax designating storage places.
Functional languages, whether static or dynamic, do not necessarily allow a destructive operation such as swapping two variables regardless of their generic capabilities.
Some static languages have difficulties with generic programming due to a lack of support for (Parametric Polymorphism).
Do your best!
|
#Metafont
|
Metafont
|
vardef swap(suffix a, b) =
save ?; string s_;
if boolean a: boolean ?
elseif numeric a: numeric ? % this one could be omitted
elseif pair a: pair ?
elseif path a: path ?
elseif pen a: pen ?
elseif picture a: picture ?
elseif string a: string ?
elseif transform a: transform ? fi;
? := a; a := b; b := ?
enddef;
|
http://rosettacode.org/wiki/Greatest_element_of_a_list
|
Greatest element of a list
|
Task
Create a function that returns the maximum value in a provided set of values,
where the number of values may not be known until run-time.
|
#Phix
|
Phix
|
with javascript_semantics
?max({1,1234,62,234,12,34,6})
?max({"ant", "antelope", "dog", "cat", "cow", "wolf", "wolverine", "aardvark"})
|
http://rosettacode.org/wiki/Greatest_common_divisor
|
Greatest common divisor
|
Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related task
least common multiple.
See also
MathWorld entry: greatest common divisor.
Wikipedia entry: greatest common divisor.
|
#MAXScript
|
MAXScript
|
fn gcdIter a b =
(
while b > 0 do
(
c = mod a b
a = b
b = c
)
abs a
)
|
http://rosettacode.org/wiki/Greatest_common_divisor
|
Greatest common divisor
|
Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related task
least common multiple.
See also
MathWorld entry: greatest common divisor.
Wikipedia entry: greatest common divisor.
|
#Mercury
|
Mercury
|
:- module gcd.
:- interface.
:- import_module integer.
:- func gcd(integer, integer) = integer.
:- implementation.
:- pragma memo(gcd/2).
gcd(A, B) = (if B = integer(0) then A else gcd(B, A mod B)).
|
http://rosettacode.org/wiki/Hailstone_sequence
|
Hailstone sequence
|
The Hailstone sequence of numbers can be generated from a starting positive integer, n by:
If n is 1 then the sequence ends.
If n is even then the next n of the sequence = n/2
If n is odd then the next n of the sequence = (3 * n) + 1
The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates.
This sequence was named by Lothar Collatz in 1937 (or possibly in 1939), and is also known as (the):
hailstone sequence, hailstone numbers
3x + 2 mapping, 3n + 1 problem
Collatz sequence
Hasse's algorithm
Kakutani's problem
Syracuse algorithm, Syracuse problem
Thwaites conjecture
Ulam's problem
The hailstone sequence is also known as hailstone numbers (because the values are usually subject to multiple descents and ascents like hailstones in a cloud).
Task
Create a routine to generate the hailstone sequence for a number.
Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1
Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.
(But don't show the actual sequence!)
See also
xkcd (humourous).
The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).
The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).
|
#ooRexx
|
ooRexx
|
sequence = hailstone(27)
say "Hailstone sequence for 27 has" sequence~items "elements and is ["sequence~toString('l', ", ")"]"
highestNumber = 1
highestCount = 1
loop i = 2 to 100000
sequence = hailstone(i)
count = sequence~items
if count > highestCount then do
highestNumber = i
highestCount = count
end
end
say "Number" highestNumber "has the longest sequence with" highestCount "elements"
-- short routine to generate a hailstone sequence
::routine hailstone
use arg n
sequence = .array~of(n)
loop while n \= 1
if n // 2 == 0 then n = n / 2
else n = 3 * n + 1
sequence~append(n)
end
return sequence
|
http://rosettacode.org/wiki/Happy_numbers
|
Happy numbers
|
From Wikipedia, the free encyclopedia:
A happy number is defined by the following process:
Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.
Those numbers for which this process end in 1 are happy numbers,
while those numbers that do not end in 1 are unhappy numbers.
Task
Find and print the first 8 happy numbers.
Display an example of your output here on this page.
See also
The OEIS entry: The happy numbers: A007770
The OEIS entry: The unhappy numbers; A031177
|
#zkl
|
zkl
|
fcn happyNumbers{ // continously spew happy numbers
foreach N in ([1..]){
n:=N; while(1){
n=n.split().reduce(fcn(p,n){ p + n*n },0);
if(n==1) { vm.yield(N); break; }
if(n==4) break; // unhappy cycle
}
}
}
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#Malbolge
|
Malbolge
|
('&%:9]!~}|z2Vxwv-,POqponl$Hjig%eB@@>}=<M:9wv6WsU2T|nm-,jcL(I&%$#"
`CB]V?Tx<uVtT`Rpo3NlF.Jh++FdbCBA@?]!~|4XzyTT43Qsqq(Lnmkj"Fhg${z@>
|
http://rosettacode.org/wiki/Generic_swap
|
Generic swap
|
Task
Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types.
If your solution language is statically typed please describe the way your language provides genericity.
If variables are typed in the given language, it is permissible that the two variables be constrained to having a mutually compatible type, such that each is permitted to hold the value previously stored in the other without a type violation.
That is to say, solutions do not have to be capable of exchanging, say, a string and integer value, if the underlying storage locations are not attributed with types that permit such an exchange.
Generic swap is a task which brings together a few separate issues in programming language semantics.
Dynamically typed languages deal with values in a generic way quite readily, but do not necessarily make it easy to write a function to destructively swap two variables, because this requires indirection upon storage places or upon the syntax designating storage places.
Functional languages, whether static or dynamic, do not necessarily allow a destructive operation such as swapping two variables regardless of their generic capabilities.
Some static languages have difficulties with generic programming due to a lack of support for (Parametric Polymorphism).
Do your best!
|
#min
|
min
|
swap
|
http://rosettacode.org/wiki/Greatest_element_of_a_list
|
Greatest element of a list
|
Task
Create a function that returns the maximum value in a provided set of values,
where the number of values may not be known until run-time.
|
#Phixmonti
|
Phixmonti
|
"1" "1234" "62" "234" "12" "34" "6" stklen tolist
dup "Alphabetic order: " print max print nl
len for
var i
i get tonum i set
endfor
"Numeric order: " print max print
|
http://rosettacode.org/wiki/Greatest_element_of_a_list
|
Greatest element of a list
|
Task
Create a function that returns the maximum value in a provided set of values,
where the number of values may not be known until run-time.
|
#PHP
|
PHP
|
max($values)
|
http://rosettacode.org/wiki/Greatest_common_divisor
|
Greatest common divisor
|
Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related task
least common multiple.
See also
MathWorld entry: greatest common divisor.
Wikipedia entry: greatest common divisor.
|
#MINIL
|
MINIL
|
// Greatest common divisor
00 0E GCD: ENT R0
01 1E ENT R1
02 21 Again: R2 = R1
03 10 Loop: R1 = R0
04 02 R0 = R2
05 2D Minus: DEC R2
06 8A JZ Stop
07 1D DEC R1
08 C5 JNZ Minus
09 83 JZ Loop
0A 1D Stop: DEC R1
0B C2 JNZ Again
0C 80 JZ GCD // Display GCD in R0
|
http://rosettacode.org/wiki/Greatest_common_divisor
|
Greatest common divisor
|
Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related task
least common multiple.
See also
MathWorld entry: greatest common divisor.
Wikipedia entry: greatest common divisor.
|
#MiniScript
|
MiniScript
|
gcd = function(a, b)
while b
temp = b
b = a % b
a = temp
end while
return abs(a)
end function
print gcd(18,12)
|
http://rosettacode.org/wiki/Hailstone_sequence
|
Hailstone sequence
|
The Hailstone sequence of numbers can be generated from a starting positive integer, n by:
If n is 1 then the sequence ends.
If n is even then the next n of the sequence = n/2
If n is odd then the next n of the sequence = (3 * n) + 1
The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates.
This sequence was named by Lothar Collatz in 1937 (or possibly in 1939), and is also known as (the):
hailstone sequence, hailstone numbers
3x + 2 mapping, 3n + 1 problem
Collatz sequence
Hasse's algorithm
Kakutani's problem
Syracuse algorithm, Syracuse problem
Thwaites conjecture
Ulam's problem
The hailstone sequence is also known as hailstone numbers (because the values are usually subject to multiple descents and ascents like hailstones in a cloud).
Task
Create a routine to generate the hailstone sequence for a number.
Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1
Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.
(But don't show the actual sequence!)
See also
xkcd (humourous).
The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).
The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).
|
#Order
|
Order
|
#include <order/interpreter.h>
#define ORDER_PP_DEF_8hailstone ORDER_PP_FN( \
8fn(8N, \
8cond((8equal(8N, 1), 8seq(1)) \
(8is_0(8remainder(8N, 2)), \
8seq_push_front(8N, 8hailstone(8quotient(8N, 2)))) \
(8else, \
8seq_push_front(8N, 8hailstone(8inc(8times(8N, 3))))))) )
ORDER_PP(
8lets((8H, 8seq_map(8to_lit, 8hailstone(27)))
(8S, 8seq_size(8H)),
8print(8(h(27) - length:) 8to_lit(8S) 8comma 8space
8(starts with:) 8seq_take(4, 8H) 8comma 8space
8(ends with:) 8seq_drop(8minus(8S, 4), 8H))
) )
|
http://rosettacode.org/wiki/Happy_numbers
|
Happy numbers
|
From Wikipedia, the free encyclopedia:
A happy number is defined by the following process:
Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.
Those numbers for which this process end in 1 are happy numbers,
while those numbers that do not end in 1 are unhappy numbers.
Task
Find and print the first 8 happy numbers.
Display an example of your output here on this page.
See also
The OEIS entry: The happy numbers: A007770
The OEIS entry: The unhappy numbers; A031177
|
#ZX_Spectrum_Basic
|
ZX Spectrum Basic
|
10 FOR i=1 TO 100
20 GO SUB 1000
30 IF isHappy=1 THEN PRINT i;" is a happy number"
40 NEXT i
50 STOP
1000 REM Is Happy?
1010 LET isHappy=0: LET count=0: LET num=i
1020 IF count=50 OR isHappy=1 THEN RETURN
1030 LET n$=STR$ (num)
1040 LET count=count+1
1050 LET isHappy=0
1060 FOR j=1 TO LEN n$
1070 LET isHappy=isHappy+VAL n$(j)^2
1080 NEXT j
1090 LET num=isHappy
1100 GO TO 1020
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#MANOOL
|
MANOOL
|
{{extern "manool.org.18/std/0.3/all"} in WriteLine[Out; "Hello world!"]}
|
http://rosettacode.org/wiki/Generic_swap
|
Generic swap
|
Task
Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types.
If your solution language is statically typed please describe the way your language provides genericity.
If variables are typed in the given language, it is permissible that the two variables be constrained to having a mutually compatible type, such that each is permitted to hold the value previously stored in the other without a type violation.
That is to say, solutions do not have to be capable of exchanging, say, a string and integer value, if the underlying storage locations are not attributed with types that permit such an exchange.
Generic swap is a task which brings together a few separate issues in programming language semantics.
Dynamically typed languages deal with values in a generic way quite readily, but do not necessarily make it easy to write a function to destructively swap two variables, because this requires indirection upon storage places or upon the syntax designating storage places.
Functional languages, whether static or dynamic, do not necessarily allow a destructive operation such as swapping two variables regardless of their generic capabilities.
Some static languages have difficulties with generic programming due to a lack of support for (Parametric Polymorphism).
Do your best!
|
#MiniScript
|
MiniScript
|
swap = function(map, a, b)
temp = map[a]
map[a] = map[b]
map[b] = temp
end function
x = 1
y = 2
print "BEFORE: x=" + x + ", y=" + y
swap(locals, "x", "y")
print "AFTER: x=" + x + ", y=" + y
|
http://rosettacode.org/wiki/Greatest_element_of_a_list
|
Greatest element of a list
|
Task
Create a function that returns the maximum value in a provided set of values,
where the number of values may not be known until run-time.
|
#PicoLisp
|
PicoLisp
|
: (max 2 4 1 3) # Return the maximal argument
-> 4
: (apply max (2 4 1 3)) # Apply to a list
-> 4
: (maxi abs (2 -4 -1 3)) # Maximum according to given function
-> -4
|
http://rosettacode.org/wiki/Greatest_element_of_a_list
|
Greatest element of a list
|
Task
Create a function that returns the maximum value in a provided set of values,
where the number of values may not be known until run-time.
|
#PL.2FI
|
PL/I
|
maximum = A(lbound(A,1));
do i = lbound(A,1)+1 to hbound(A,1);
if maximum < A(i) then maximum = A(i);
end;
|
http://rosettacode.org/wiki/Greatest_common_divisor
|
Greatest common divisor
|
Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related task
least common multiple.
See also
MathWorld entry: greatest common divisor.
Wikipedia entry: greatest common divisor.
|
#MiniZinc
|
MiniZinc
|
function var int: gcd(int:a2,int:b2) =
let {
int:a1 = max(a2,b2);
int:b1 = min(a2,b2);
array[0..a1,0..b1] of var int: gcd;
constraint forall(a in 0..a1)(
forall(b in 0..b1)(
gcd[a,b] ==
if (b == 0) then
a
else
gcd[b, a mod b]
endif
)
)
} in gcd[a1,b1];
var int: gcd1 = gcd(8,12);
solve satisfy;
output [show(gcd1),"\n"];
|
http://rosettacode.org/wiki/Greatest_common_divisor
|
Greatest common divisor
|
Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related task
least common multiple.
See also
MathWorld entry: greatest common divisor.
Wikipedia entry: greatest common divisor.
|
#MIPS_Assembly
|
MIPS Assembly
|
gcd:
# a0 and a1 are the two integer parameters
# return value is in v0
move $t0, $a0
move $t1, $a1
loop:
beq $t1, $0, done
div $t0, $t1
move $t0, $t1
mfhi $t1
j loop
done:
move $v0, $t0
jr $ra
|
http://rosettacode.org/wiki/Hailstone_sequence
|
Hailstone sequence
|
The Hailstone sequence of numbers can be generated from a starting positive integer, n by:
If n is 1 then the sequence ends.
If n is even then the next n of the sequence = n/2
If n is odd then the next n of the sequence = (3 * n) + 1
The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates.
This sequence was named by Lothar Collatz in 1937 (or possibly in 1939), and is also known as (the):
hailstone sequence, hailstone numbers
3x + 2 mapping, 3n + 1 problem
Collatz sequence
Hasse's algorithm
Kakutani's problem
Syracuse algorithm, Syracuse problem
Thwaites conjecture
Ulam's problem
The hailstone sequence is also known as hailstone numbers (because the values are usually subject to multiple descents and ascents like hailstones in a cloud).
Task
Create a routine to generate the hailstone sequence for a number.
Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1
Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.
(But don't show the actual sequence!)
See also
xkcd (humourous).
The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).
The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).
|
#Oz
|
Oz
|
declare
fun {HailstoneSeq N}
N > 0 = true %% assert
if N == 1 then [1]
elseif {IsEven N} then N|{HailstoneSeq N div 2}
else N|{HailstoneSeq 3*N+1}
end
end
HSeq27 = {HailstoneSeq 27}
{Length HSeq27} = 112
{List.take HSeq27 4} = [27 82 41 124]
{List.drop HSeq27 108} = [8 4 2 1]
fun {MaxBy2nd A=A1#A2 B=B1#B2}
if B2 > A2 then B else A end
end
Pairs = {Map {List.number 1 99999 1}
fun {$ I} I#{Length {HailstoneSeq I}} end}
MaxI#MaxLen = {List.foldL Pairs MaxBy2nd 0#0}
{System.showInfo
"Maximum length "#MaxLen#" was found for hailstone("#MaxI#")"}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.