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/Gray_code
|
Gray code
|
Gray code
Karnaugh maps
Create functions to encode a number to and decode a number from Gray code.
Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary).
There are many possible Gray codes. The following encodes what is called "binary reflected Gray code."
Encoding (MSB is bit 0, b is binary, g is Gray code):
if b[i-1] = 1
g[i] = not b[i]
else
g[i] = b[i]
Or:
g = b xor (b logically right shifted 1 time)
Decoding (MSB is bit 0, b is binary, g is Gray code):
b[0] = g[0]
for other bits:
b[i] = g[i] xor b[i-1]
Reference
Converting Between Gray and Binary Codes. It includes step-by-step animations.
|
#Pascal
|
Pascal
|
sub bin2gray
{
return $_[0] ^ ($_[0] >> 1);
}
sub gray2bin
{
my ($num)= @_;
my $bin= $num;
while( $num >>= 1 ) {
# a bit ends up flipped iff an odd number of bits to its left is set.
$bin ^= $num; # different from the suggested algorithm;
} # avoids using bit mask and explicit bittery
return $bin;
}
for (0..31) {
my $gr= bin2gray($_);
printf "%d\t%b\t%b\t%b\n", $_, $_, $gr, gray2bin($gr);
}
|
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!
|
#Burlesque
|
Burlesque
|
\/
|
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.
|
#CoffeeScript
|
CoffeeScript
|
# using Math library
max1 = (list) ->
Math.max.apply null, list
# using no libraries
max2 = (list) ->
maxVal = list[0]
for value in list
maxVal = value if value > maxVal
maxVal
# Test it
a = [0,1,2,5,4];
alert(max1(a)+". The answer is "+max2(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.
|
#Befunge
|
Befunge
|
#v&< @.$<
:<\g05%p05:_^#
|
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).
|
#CoffeeScript
|
CoffeeScript
|
hailstone = (n) ->
if n is 1
[n]
else if n % 2 is 0
[n].concat hailstone n/2
else
[n].concat hailstone (3*n) + 1
h27 = hailstone 27
console.log "hailstone(27) = #{h27[0..3]} ... #{h27[-4..]} (length: #{h27.length})"
maxlength = 0
maxnums = []
for i in [1..100000]
seq = hailstone i
if seq.length is maxlength
maxnums.push i
else if seq.length > maxlength
maxlength = seq.length
maxnums = [i]
console.log "Max length: #{maxlength}; numbers generating sequences of this length: #{maxnums}"
|
http://rosettacode.org/wiki/Hamming_numbers
|
Hamming numbers
|
Hamming numbers are numbers of the form
H = 2i × 3j × 5k
where
i, j, k ≥ 0
Hamming numbers are also known as ugly numbers and also 5-smooth numbers (numbers whose prime divisors are less or equal to 5).
Task
Generate the sequence of Hamming numbers, in increasing order. In particular:
Show the first twenty Hamming numbers.
Show the 1691st Hamming number (the last one below 231).
Show the one millionth Hamming number (if the language – or a convenient library – supports arbitrary-precision integers).
Related tasks
Humble numbers
N-smooth numbers
References
Wikipedia entry: Hamming numbers (this link is re-directed to Regular number).
Wikipedia entry: Smooth number
OEIS entry: A051037 5-smooth or Hamming numbers
Hamming problem from Dr. Dobb's CodeTalk (dead link as of Sep 2011; parts of the thread here and here).
|
#Logo
|
Logo
|
to init.ham
; queues
make "twos [1]
make "threes [1]
make "fives [1]
end
to next.ham
localmake "ham first :twos
if less? first :threes :ham [make "ham first :threes]
if less? first :fives :ham [make "ham first :fives]
if equal? :ham first :twos [ignore dequeue "twos]
if equal? :ham first :threes [ignore dequeue "threes]
if equal? :ham first :fives [ignore dequeue "fives]
queue "twos :ham * 2
queue "threes :ham * 3
queue "fives :ham * 5
output :ham
end
init.ham
repeat 20 [print next.ham]
repeat 1690-20 [ignore next.ham]
print next.ham
|
http://rosettacode.org/wiki/Guess_the_number
|
Guess the number
|
Task
Write a program where the program chooses a number between 1 and 10.
A player is then prompted to enter a guess. If the player guesses wrong, then the prompt appears again until the guess is correct.
When the player has made a successful guess the computer will issue a "Well guessed!" message, and the program exits.
A conditional loop may be used to repeat the guessing until the user is correct.
Related tasks
Bulls and cows
Bulls and cows/Player
Guess the number/With Feedback
Mastermind
|
#Perl
|
Perl
|
my $number = 1 + int rand 10;
do { print "Guess a number between 1 and 10: " } until <> == $number;
print "You got it!\n";
|
http://rosettacode.org/wiki/Guess_the_number
|
Guess the number
|
Task
Write a program where the program chooses a number between 1 and 10.
A player is then prompted to enter a guess. If the player guesses wrong, then the prompt appears again until the guess is correct.
When the player has made a successful guess the computer will issue a "Well guessed!" message, and the program exits.
A conditional loop may be used to repeat the guessing until the user is correct.
Related tasks
Bulls and cows
Bulls and cows/Player
Guess the number/With Feedback
Mastermind
|
#Phix
|
Phix
|
--
-- demo\rosetta\Guess_the_number.exw
--
with javascript_semantics
include pGUI.e
integer secret = rand(10)
function valuechanged_cb(Ihandle guess)
integer n = IupGetInt(guess,"VALUE")
if n=secret then
Ihandle lbl = IupGetBrother(guess,true)
IupSetAttribute(lbl,"TITLE","Your guess was correct")
IupRefresh(lbl)
IupSetInt(guess,"ACTIVE",false)
end if
return IUP_DEFAULT
end function
procedure main()
IupOpen()
Ihandle lbl = IupLabel("Your guess","RASTERSIZE=58x21"),
guess = IupText("VALUECHANGED_CB", Icallback("valuechanged_cb"),
"RASTERSIZE=21x21"),
dlg = IupDialog(IupVbox({IupFill(),
IupHbox({IupFill(),lbl,guess,IupFill()},
"GAP=10"),
IupFill()}),
`MINSIZE=300x100,TITLE="Guess the number"`)
IupShow(dlg)
IupSetAttribute(lbl,"RASTERSIZE","x21")
if platform()!=JS then
IupMainLoop()
IupClose()
end if
end procedure
main()
|
http://rosettacode.org/wiki/Greatest_subsequential_sum
|
Greatest subsequential sum
|
Task
Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one.
An empty subsequence is considered to have the sum of 0; thus if all elements are negative, the result must be the empty sequence.
|
#PL.2FI
|
PL/I
|
*process source attributes xref;
ss: Proc Options(Main);
/* REXX ***************************************************************
* 26.08.2013 Walter Pachl translated from REXX version 3
**********************************************************************/
Dcl HBOUND builtin;
Dcl SYSPRINT Print;
Dcl (I,J,LB,MAXSUM,SEQEND,SEQSTART,SEQSUM) Bin Fixed(15);
Dcl s(11) Bin Fixed(15) Init(-1,-2,3,5,6,-2,-1,4,-4,2,-1);
maxSum = 0;
seqStart = 0;
seqEnd = -1;
do i = 1 To hbound(s);
seqSum = 0;
Do j = i to hbound(s);
seqSum = seqSum + s(j);
if seqSum > maxSum then Do;
maxSum = seqSum;
seqStart = i;
seqEnd = j;
end;
end;
end;
Put Edit('Sequence:')(Skip,a);
Put Edit('')(Skip,a);
Do i=1 To hbound(s);
Put Edit(s(i))(f(3));
End;
Put Edit('Subsequence with greatest sum:')(Skip,a);
If seqend<seqstart Then
Put Edit('empty')(Skip,a);
Else Do;
/*ol=copies(' ',seqStart-1)*/
lb=(seqStart-1)*3;
Put Edit(' ')(Skip,a(lb));
Do i = seqStart to seqEnd;
Put Edit(s(i))(f(3));
End;
Put Edit('Sum:',maxSum)(Skip,a,f(5));
End;
End;
|
http://rosettacode.org/wiki/Guess_the_number/With_feedback
|
Guess the number/With feedback
|
Task
Write a game (computer program) that follows the following rules:
The computer chooses a number between given set limits.
The player is asked for repeated guesses until the the target number is guessed correctly
At each guess, the computer responds with whether the guess is:
higher than the target,
equal to the target,
less than the target, or
the input was inappropriate.
Related task
Guess the number/With Feedback (Player)
|
#Julia
|
Julia
|
function guesswithfeedback(n::Integer)
number = rand(1:n)
print("I choose a number between 1 and $n\nYour guess? ")
while (guess = readline()) != dec(number)
if all(isdigit, guess)
print("Too ", parse(Int, guess) < number ? "small" : "big")
else
print("Enter an integer please")
end
print(", new guess? ")
end
println("You guessed right!")
end
guesswithfeedback(10)
|
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
|
#Liberty_BASIC
|
Liberty BASIC
|
ct = 0
n = 0
DO
n = n + 1
IF HappyN(n, sqrInt$) = 1 THEN
ct = ct + 1
PRINT ct, n
END IF
LOOP UNTIL ct = 8
END
FUNCTION HappyN(n, sqrInts$)
n$ = Str$(n)
sqrInts = 0
FOR i = 1 TO Len(n$)
sqrInts = sqrInts + Val(Mid$(n$, i, 1)) ^ 2
NEXT i
IF sqrInts = 1 THEN
HappyN = 1
EXIT FUNCTION
END IF
IF Instr(sqrInts$, ":";Str$(sqrInts);":") > 0 THEN
HappyN = 0
EXIT FUNCTION
END IF
sqrInts$ = sqrInts$ + Str$(sqrInts) + ":"
HappyN = HappyN(sqrInts, sqrInts$)
END FUNCTION
|
http://rosettacode.org/wiki/Haversine_formula
|
Haversine formula
|
This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The haversine formula is an equation important in navigation, giving great-circle distances between two points on a sphere from their longitudes and latitudes.
It is a special case of a more general formula in spherical trigonometry, the law of haversines, relating the sides and angles of spherical "triangles".
Task
Implement a great-circle distance function, or use a library function,
to show the great-circle distance between:
Nashville International Airport (BNA) in Nashville, TN, USA, which is:
N 36°7.2', W 86°40.2' (36.12, -86.67) -and-
Los Angeles International Airport (LAX) in Los Angeles, CA, USA, which is:
N 33°56.4', W 118°24.0' (33.94, -118.40)
User Kaimbridge clarified on the Talk page:
-- 6371.0 km is the authalic radius based on/extracted from surface area;
-- 6372.8 km is an approximation of the radius of the average circumference
(i.e., the average great-elliptic or great-circle radius), where the
boundaries are the meridian (6367.45 km) and the equator (6378.14 km).
Using either of these values results, of course, in differing distances:
6371.0 km -> 2886.44444283798329974715782394574671655 km;
6372.8 km -> 2887.25995060711033944886005029688505340 km;
(results extended for accuracy check: Given that the radii are only
approximations anyways, .01' ≈ 1.0621333 km and .001" ≈ .00177 km,
practical precision required is certainly no greater than about
.0000001——i.e., .1 mm!)
As distances are segments of great circles/circumferences, it is
recommended that the latter value (r = 6372.8 km) be used (which
most of the given solutions have already adopted, anyways).
Most of the examples below adopted Kaimbridge's recommended value of
6372.8 km for the earth radius. However, the derivation of this
ellipsoidal quadratic mean radius
is wrong (the averaging over azimuth is biased). When applying these
examples in real applications, it is better to use the
mean earth radius,
6371 km. This value is recommended by the International Union of
Geodesy and Geophysics and it minimizes the RMS relative error between the
great circle and geodesic distance.
|
#Vlang
|
Vlang
|
import math
fn haversine(h f64) f64 {
return .5 * (1 - math.cos(h))
}
struct Pos {
lat f64 // latitude, radians
long f64 // longitude, radians
}
fn deg_pos(lat f64, lon f64) Pos {
return Pos{lat * math.pi / 180, lon * math.pi / 180}
}
const r_earth = 6372.8 // km
fn hs_dist(p1 Pos, p2 Pos) f64 {
return 2 * r_earth * math.asin(math.sqrt(haversine(p2.lat-p1.lat)+
math.cos(p1.lat)*math.cos(p2.lat)*haversine(p2.long-p1.long)))
}
fn main() {
println(hs_dist(deg_pos(36.12, -86.67), deg_pos(33.94, -118.40)))
}
|
http://rosettacode.org/wiki/Haversine_formula
|
Haversine formula
|
This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The haversine formula is an equation important in navigation, giving great-circle distances between two points on a sphere from their longitudes and latitudes.
It is a special case of a more general formula in spherical trigonometry, the law of haversines, relating the sides and angles of spherical "triangles".
Task
Implement a great-circle distance function, or use a library function,
to show the great-circle distance between:
Nashville International Airport (BNA) in Nashville, TN, USA, which is:
N 36°7.2', W 86°40.2' (36.12, -86.67) -and-
Los Angeles International Airport (LAX) in Los Angeles, CA, USA, which is:
N 33°56.4', W 118°24.0' (33.94, -118.40)
User Kaimbridge clarified on the Talk page:
-- 6371.0 km is the authalic radius based on/extracted from surface area;
-- 6372.8 km is an approximation of the radius of the average circumference
(i.e., the average great-elliptic or great-circle radius), where the
boundaries are the meridian (6367.45 km) and the equator (6378.14 km).
Using either of these values results, of course, in differing distances:
6371.0 km -> 2886.44444283798329974715782394574671655 km;
6372.8 km -> 2887.25995060711033944886005029688505340 km;
(results extended for accuracy check: Given that the radii are only
approximations anyways, .01' ≈ 1.0621333 km and .001" ≈ .00177 km,
practical precision required is certainly no greater than about
.0000001——i.e., .1 mm!)
As distances are segments of great circles/circumferences, it is
recommended that the latter value (r = 6372.8 km) be used (which
most of the given solutions have already adopted, anyways).
Most of the examples below adopted Kaimbridge's recommended value of
6372.8 km for the earth radius. However, the derivation of this
ellipsoidal quadratic mean radius
is wrong (the averaging over azimuth is biased). When applying these
examples in real applications, it is better to use the
mean earth radius,
6371 km. This value is recommended by the International Union of
Geodesy and Geophysics and it minimizes the RMS relative error between the
great circle and geodesic distance.
|
#Wren
|
Wren
|
var R = 6372.8 // Earth's approximate radius in kilometers.
/* Class containing trig methods which work with degrees rather than radians. */
class D {
static deg2Rad(deg) { (deg*Num.pi/180 + 2*Num.pi) % (2*Num.pi) }
static sin(d) { deg2Rad(d).sin }
static cos(d) { deg2Rad(d).cos }
}
var haversine = Fn.new { |lat1, lon1, lat2, lon2|
var dlat = lat2 - lat1
var dlon = lon2 - lon1
return 2 * R * (D.sin(dlat/2).pow(2) + D.cos(lat1) * D.cos(lat2) * D.sin(dlon/2).pow(2)).sqrt.asin
}
System.print(haversine.call(36.12, -86.67, 33.94, -118.4))
|
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
|
#IDL
|
IDL
|
print,'Hello world!'
|
http://rosettacode.org/wiki/Harshad_or_Niven_series
|
Harshad or Niven series
|
The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits.
For example, 42 is a Harshad number as 42 is divisible by (4 + 2) without remainder.
Assume that the series is defined as the numbers in increasing order.
Task
The task is to create a function/method/procedure to generate successive members of the Harshad sequence.
Use it to:
list the first 20 members of the sequence, and
list the first Harshad number greater than 1000.
Show your output here.
Related task
Increasing gaps between consecutive Niven numbers
See also
OEIS: A005349
|
#Whitespace
|
Whitespace
| |
http://rosettacode.org/wiki/Hello_world/Graphical
|
Hello world/Graphical
|
Task
Display the string Goodbye, World! on a GUI object (alert box, plain window, text area, etc.).
Related task
Hello world/Text
|
#Python
|
Python
|
import bpy
# select default cube
bpy.data.objects['Cube'].select_set(True)
# delete default cube
bpy.ops.object.delete(True)
# add text to Blender scene
bpy.data.curves.new(type="FONT", name="Font Curve").body = "Hello World"
font_obj = bpy.data.objects.new(name="Font Object", object_data=bpy.data.curves["Font Curve"])
bpy.context.scene.collection.objects.link(font_obj)
# camera center to text
bpy.context.scene.camera.location = (2.5,0.3,10)
# camera orient angle to text
bpy.context.scene.camera.rotation_euler = (0,0,0)
# change 3D scene to view from the camera
area = next(area for area in bpy.context.screen.areas if area.type == 'VIEW_3D')
area.spaces[0].region_3d.view_perspective = 'CAMERA'
|
http://rosettacode.org/wiki/Gray_code
|
Gray code
|
Gray code
Karnaugh maps
Create functions to encode a number to and decode a number from Gray code.
Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary).
There are many possible Gray codes. The following encodes what is called "binary reflected Gray code."
Encoding (MSB is bit 0, b is binary, g is Gray code):
if b[i-1] = 1
g[i] = not b[i]
else
g[i] = b[i]
Or:
g = b xor (b logically right shifted 1 time)
Decoding (MSB is bit 0, b is binary, g is Gray code):
b[0] = g[0]
for other bits:
b[i] = g[i] xor b[i-1]
Reference
Converting Between Gray and Binary Codes. It includes step-by-step animations.
|
#Perl
|
Perl
|
sub bin2gray
{
return $_[0] ^ ($_[0] >> 1);
}
sub gray2bin
{
my ($num)= @_;
my $bin= $num;
while( $num >>= 1 ) {
# a bit ends up flipped iff an odd number of bits to its left is set.
$bin ^= $num; # different from the suggested algorithm;
} # avoids using bit mask and explicit bittery
return $bin;
}
for (0..31) {
my $gr= bin2gray($_);
printf "%d\t%b\t%b\t%b\n", $_, $_, $gr, gray2bin($gr);
}
|
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!
|
#C
|
C
|
void swap(void *va, void *vb, size_t s)
{
char t, *a = (char*)va, *b = (char*)vb;
while(s--)
t = a[s], a[s] = b[s], b[s] = 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.
|
#ColdFusion
|
ColdFusion
|
<Cfset theList = '1, 1000, 250, 13'>
<Cfparam name="maxNum" default=0>
<Cfloop list="#theList#" index="i">
<Cfif i gt maxNum><Cfset maxNum = i></Cfif>
</Cfloop>
<Cfoutput>#maxNum#</Cfoutput>
|
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.
|
#BQN
|
BQN
|
Gcd ← {𝕨(|𝕊⍟(>⟜0)⊣)𝕩}
|
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).
|
#Common_Lisp
|
Common Lisp
|
(defun hailstone (n)
(cond ((= n 1) '(1))
((evenp n) (cons n (hailstone (/ n 2))))
(t (cons n (hailstone (+ (* 3 n) 1))))))
(defun longest (n)
(let ((k 0) (l 0))
(loop for i from 1 below n do
(let ((len (length (hailstone i))))
(when (> len l) (setq l len k i)))
finally (format t "Longest hailstone sequence under ~A for ~A, having length ~A." n k l))))
|
http://rosettacode.org/wiki/Hamming_numbers
|
Hamming numbers
|
Hamming numbers are numbers of the form
H = 2i × 3j × 5k
where
i, j, k ≥ 0
Hamming numbers are also known as ugly numbers and also 5-smooth numbers (numbers whose prime divisors are less or equal to 5).
Task
Generate the sequence of Hamming numbers, in increasing order. In particular:
Show the first twenty Hamming numbers.
Show the 1691st Hamming number (the last one below 231).
Show the one millionth Hamming number (if the language – or a convenient library – supports arbitrary-precision integers).
Related tasks
Humble numbers
N-smooth numbers
References
Wikipedia entry: Hamming numbers (this link is re-directed to Regular number).
Wikipedia entry: Smooth number
OEIS entry: A051037 5-smooth or Hamming numbers
Hamming problem from Dr. Dobb's CodeTalk (dead link as of Sep 2011; parts of the thread here and here).
|
#Lua
|
Lua
|
function hiter()
hammings = {1}
prev, vals = {1, 1, 1}
index = 1
local function nextv()
local n, v = 1, hammings[prev[1]]*2
if hammings[prev[2]]*3 < v then n, v = 2, hammings[prev[2]]*3 end
if hammings[prev[3]]*5 < v then n, v = 3, hammings[prev[3]]*5 end
prev[n] = prev[n] + 1
if hammings[index] == v then return nextv() end
index = index + 1
hammings[index] = v
return v
end
return nextv
end
j = hiter()
for i = 1, 20 do
print(j())
end
n, l = 0, 0
while n < 2^31 do n, l = j(), n end
print(l)
|
http://rosettacode.org/wiki/Guess_the_number
|
Guess the number
|
Task
Write a program where the program chooses a number between 1 and 10.
A player is then prompted to enter a guess. If the player guesses wrong, then the prompt appears again until the guess is correct.
When the player has made a successful guess the computer will issue a "Well guessed!" message, and the program exits.
A conditional loop may be used to repeat the guessing until the user is correct.
Related tasks
Bulls and cows
Bulls and cows/Player
Guess the number/With Feedback
Mastermind
|
#PHP
|
PHP
|
<?php
session_start();
if(isset($_SESSION['number']))
{
$number = $_SESSION['number'];
}
else
{
$_SESSION['number'] = rand(1,10);
}
if(isset($_POST["guess"])){
if($_POST["guess"]){
$guess = htmlspecialchars($_POST['guess']);
echo $guess . "<br />";
if ($guess != $number)
{
echo "Your guess is not correct";
}
elseif($guess == $number)
{
echo "You got the correct number!";
}
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Guess A Number</title>
</head>
<body>
<form action="<?=$_SERVER['PHP_SELF'] ?>" method="post" name="guess-a-number">
<label for="guess">Guess number:</label><br/ >
<input type="text" name="guess" />
<input name="number" type="hidden" value="<?= $number ?>" />
<input name="submit" type="submit" />
</form>
</body>
</html>
|
http://rosettacode.org/wiki/Greatest_subsequential_sum
|
Greatest subsequential sum
|
Task
Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one.
An empty subsequence is considered to have the sum of 0; thus if all elements are negative, the result must be the empty sequence.
|
#Potion
|
Potion
|
gss = (lst) :
# Find discrete integral
integral = (0)
accum = 0
lst each (n): accum = accum + n, integral append(accum).
# Check integral[b + 1] - integral[a] for all 0 <= a <= b < N
max = -1
max_a = 0
max_b = 0
lst length times (b) :
b times (a) :
if (integral(b + 1) - integral(a) > max) :
max = integral(b + 1) - integral(a)
max_a = a
max_b = b
.
.
.
# Print the results
if (max >= 0) :
(lst slice(max_a, max_b) join(" + "), " = ", max, "\n") join print
.
else :
"No subsequence larger than 0\n" print
.
.
gss((-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1))
gss((-1, -2, -3, -4, -5))
gss((7,-6, -8, 5, -2, -6, 7, 4, 8, -9, -3, 2, 6, -4, -6))
|
http://rosettacode.org/wiki/Greatest_subsequential_sum
|
Greatest subsequential sum
|
Task
Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one.
An empty subsequence is considered to have the sum of 0; thus if all elements are negative, the result must be the empty sequence.
|
#Prolog
|
Prolog
|
:- use_module(library(chr)).
:- chr_constraint
init_chr/2,
seq/2,
% gss(Deb, Len, TT)
gss/3,
% gsscur(Deb, Len, TT, IdCur)
gsscur/4,
memoseq/3,
clean/0,
greatest_subsequence/0.
greatest_subsequence <=>
L = [-1 , -2 , 3 , 5 , 6 , -2 , -1 , 4 , -4 , 2 , -1],
init_chr(1, L),
find_chr_constraint(gss(Deb, Len, V)),
clean,
writeln(L),
forall(between(1, Len, I),
( J is I+Deb-1, nth1(J, L, N), format('~w ', [N]))),
format('==> ~w ~n', [V]).
% destroy last constraint gss
clean \ gss(_,_,_) <=> true.
clean <=> true.
init_chr_end @ init_chr(_, []) <=> gss(0, 0, 0), gsscur(1,0,0,1).
init_chr_loop @ init_chr(N, [H|T]) <=> seq(N, H), N1 is N+1, init_chr(N1, T).
% here, we memorize the list
gsscur_with_negative @ gsscur(Deb, Len, TT, N), seq(N, V) <=> V =< 0 |
memoseq(Deb, Len, TT),
TT1 is TT + V,
N1 is N+1,
% if TT1 becomes negative,
% we begin a new subsequence
( TT1 < 0 -> gsscur(N1,0,0,N1)
; Len1 is Len + 1, gsscur(Deb, Len1, TT1, N1)).
gsscur_with_positive @ gsscur(Deb, Len, TT, N), seq(N, V) <=> V > 0 |
TT1 is TT + V,
N1 is N+1,
Len1 is Len + 1,
gsscur(Deb, Len1, TT1, N1).
gsscur_end @ gsscur(Deb, Len, TT, _N) <=> memoseq(Deb, Len, TT).
memoseq(_DC, _LC, TTC), gss(D, L, TT) <=> TTC =< TT |
gss(D, L, TT).
memoseq(DC, LC, TTC), gss(_D, _L, TT) <=> TTC > TT |
gss(DC, LC, TTC).
|
http://rosettacode.org/wiki/Guess_the_number/With_feedback
|
Guess the number/With feedback
|
Task
Write a game (computer program) that follows the following rules:
The computer chooses a number between given set limits.
The player is asked for repeated guesses until the the target number is guessed correctly
At each guess, the computer responds with whether the guess is:
higher than the target,
equal to the target,
less than the target, or
the input was inappropriate.
Related task
Guess the number/With Feedback (Player)
|
#Kotlin
|
Kotlin
|
import kotlin.random.Random
fun main() {
val n = 1 + rand.nextInt(20)
println("Guess which number I've chosen in the range 1 to 20\n")
while (true) {
print(" Your guess : ")
val guess = readLine()?.toInt()
when (guess) {
n -> { println("Correct, well guessed!") ; return }
in n + 1 .. 20 -> println("Your guess is higher than the chosen number, try again")
in 1 .. n - 1 -> println("Your guess is lower than the chosen number, try again")
else -> println("Your guess is inappropriate, try again")
}
}
}
|
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
|
#Locomotive_Basic
|
Locomotive Basic
|
10 mode 1:defint a-z
20 for i=1 to 100
30 i2=i
40 for l=1 to 20
50 a$=str$(i2)
60 i2=0
70 for j=1 to len(a$)
80 d=val(mid$(a$,j,1))
90 i2=i2+d*d
100 next j
110 if i2=1 then print i;"is a happy number":n=n+1:goto 150
120 if i2=4 then 150 ' cycle found
130 next l
140 ' check if we have reached 8 numbers yet
150 if n=8 then end
160 next i
|
http://rosettacode.org/wiki/Haversine_formula
|
Haversine formula
|
This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The haversine formula is an equation important in navigation, giving great-circle distances between two points on a sphere from their longitudes and latitudes.
It is a special case of a more general formula in spherical trigonometry, the law of haversines, relating the sides and angles of spherical "triangles".
Task
Implement a great-circle distance function, or use a library function,
to show the great-circle distance between:
Nashville International Airport (BNA) in Nashville, TN, USA, which is:
N 36°7.2', W 86°40.2' (36.12, -86.67) -and-
Los Angeles International Airport (LAX) in Los Angeles, CA, USA, which is:
N 33°56.4', W 118°24.0' (33.94, -118.40)
User Kaimbridge clarified on the Talk page:
-- 6371.0 km is the authalic radius based on/extracted from surface area;
-- 6372.8 km is an approximation of the radius of the average circumference
(i.e., the average great-elliptic or great-circle radius), where the
boundaries are the meridian (6367.45 km) and the equator (6378.14 km).
Using either of these values results, of course, in differing distances:
6371.0 km -> 2886.44444283798329974715782394574671655 km;
6372.8 km -> 2887.25995060711033944886005029688505340 km;
(results extended for accuracy check: Given that the radii are only
approximations anyways, .01' ≈ 1.0621333 km and .001" ≈ .00177 km,
practical precision required is certainly no greater than about
.0000001——i.e., .1 mm!)
As distances are segments of great circles/circumferences, it is
recommended that the latter value (r = 6372.8 km) be used (which
most of the given solutions have already adopted, anyways).
Most of the examples below adopted Kaimbridge's recommended value of
6372.8 km for the earth radius. However, the derivation of this
ellipsoidal quadratic mean radius
is wrong (the averaging over azimuth is biased). When applying these
examples in real applications, it is better to use the
mean earth radius,
6371 km. This value is recommended by the International Union of
Geodesy and Geophysics and it minimizes the RMS relative error between the
great circle and geodesic distance.
|
#X86_Assembly
|
X86 Assembly
|
0000 .model tiny
0000 .code
.486
org 100h ;.com files start here
0100 9B DB E3 start: finit ;initialize floating-point unit (FPU)
;Great circle distance =
; 2.0*Radius * ASin( sqrt( Haversine(Lat2-Lat1) +
; Haversine(Lon2-Lon1)*Cos(Lat1)*Cos(Lat2) ) )
0103 D9 06 0191r fld Lat2 ;push real onto FPU stack
0107 D8 26 018Dr fsub Lat1 ;subtract real from top of stack (st(0) = st)
010B E8 0070 call Haversine ;(1.0-cos(st)) / 2.0
010E D9 06 0199r fld Lon2 ;repeat for longitudes
0112 D8 26 0195r fsub Lon1
0116 E8 0065 call Haversine ;st(1)=Lats; st=Lons
0119 D9 06 018Dr fld Lat1
011D D9 FF fcos ;replace st with its cosine
011F D9 06 0191r fld Lat2
0123 D9 FF fcos ;st=cos(Lat2); st(1)=cos(Lat1); st(2)=Lats; st(3)=Lons
0125 DE C9 fmul ;st=cos(Lat2)*cos(Lat1); st(1)=Lats; st(2)=Lons
0127 DE C9 fmul ;st=cos(Lat2)*cos(Lat1)*Lats; st(1)=Lons
0129 DE C1 fadd ;st=cos(Lat2)*cos(Lat1)*Lats + Lons
012B D9 FA fsqrt ;replace st with its square root
;asin(x) = atan(x/sqrt(1-x^2))
012D D9 C0 fld st ;duplicate tos
012F D8 C8 fmul st, st ;x^2
0131 D9 E8 fld1 ;get 1.0
0133 DE E1 fsubr ;1 - x^2
0135 D9 FA fsqrt ;sqrt(1-x^2)
0137 D9 F3 fpatan ;take atan(st(1)/st)
0139 D8 0E 019Dr fmul Radius2 ;*2.0*Radius
;Display value in FPU's top of stack (st)
=0004 before equ 4 ;places before
=0002 after equ 2 ; and after decimal point
=0001 scaler = 1 ;"=" allows scaler to be redefined, unlike equ
rept after ;repeat block "after" times
scaler = scaler*10
endm ;scaler now = 10^after
013D 66| 6A 64 push dword ptr scaler;use stack for convenient memory location
0140 67| DA 0C 24 fimul dword ptr [esp] ;st:= st*scaler
0144 67| DB 1C 24 fistp dword ptr [esp] ;round st to nearest integer
0148 66| 58 pop eax ; and put it into eax
014A 66| BB 0000000A mov ebx, 10 ;set up for idiv instruction
0150 B9 0006 mov cx, before+after;set up loop counter
0153 66| 99 ro10: cdq ;convert double to quad; i.e: edx:= 0
0155 66| F7 FB idiv ebx ;eax:= edx:eax/ebx; remainder in edx
0158 52 push dx ;save least significant digit on stack
0159 E2 F8 loop ro10 ;cx--; loop back if not zero
015B B1 06 mov cl, before+after;(ch=0)
015D B3 00 mov bl, 0 ;used to suppress leading zeros
015F 58 ro20: pop ax ;get digit
0160 0A D8 or bl, al ;turn off suppression if not a zero
0162 80 F9 03 cmp cl, after+1 ;is digit immediately to left of decimal point?
0165 75 01 jne ro30 ;skip if not
0167 43 inc bx ;turn off leading zero suppression
0168 04 30 ro30: add al, '0' ;if leading zero then ' ' else add 0
016A 84 DB test bl, bl
016C 75 02 jne ro40
016E B0 20 mov al, ' '
0170 CD 29 ro40: int 29h ;display character in al register
0172 80 F9 03 cmp cl, after+1 ;is digit immediately to left of decimal point?
0175 75 04 jne ro50 ;skip if not
0177 B0 2E mov al, '.' ;display decimal point
0179 CD 29 int 29h
017B E2 E2 ro50: loop ro20 ;loop until all digits displayed
017D C3 ret ;return to OS
017E Haversine: ;return (1.0-Cos(Ang)) / 2.0 in st
017E D9 FF fcos
0180 D9 E8 fld1
0182 DE E1 fsubr
0184 D8 36 0189r fdiv N2
0188 C3 ret
0189 40000000 N2 dd 2.0
018D 3F21628D Lat1 dd 0.63041 ;36.12*pi/180
0191 3F17A4E8 Lat2 dd 0.59236 ;33.94*pi/180
0195 BFC19F80 Lon1 dd -1.51268 ;-86.67*pi/180
0199 C004410B Lon2 dd -2.06647 ;-118.40*pi/180
019D 46472666 Radius2 dd 12745.6 ;6372.8 average radius of Earth (km) times 2
;(TASM isn't smart enough to do floating point constant calculations)
end start
|
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
|
#Idris
|
Idris
|
module Main
main : IO ()
main = putStrLn "Hello world!"
|
http://rosettacode.org/wiki/Harshad_or_Niven_series
|
Harshad or Niven series
|
The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits.
For example, 42 is a Harshad number as 42 is divisible by (4 + 2) without remainder.
Assume that the series is defined as the numbers in increasing order.
Task
The task is to create a function/method/procedure to generate successive members of the Harshad sequence.
Use it to:
list the first 20 members of the sequence, and
list the first Harshad number greater than 1000.
Show your output here.
Related task
Increasing gaps between consecutive Niven numbers
See also
OEIS: A005349
|
#Wren
|
Wren
|
var niven = Fiber.new {
var n = 1
while (true) {
var i = n
var sum = 0
while (i > 0) {
sum = sum + i%10
i = (i/10).floor
}
if (n%sum == 0) Fiber.yield(n)
n = n + 1
}
}
System.print("The first 20 Niven numbers are:")
for (i in 1..20) {
System.write("%(niven.call()) ")
}
System.write("\n\nThe first Niven number greater than 1000 is: ")
while (true) {
var niv = niven.call()
if (niv > 1000) {
System.print(niv)
break
}
}
|
http://rosettacode.org/wiki/Hello_world/Graphical
|
Hello world/Graphical
|
Task
Display the string Goodbye, World! on a GUI object (alert box, plain window, text area, etc.).
Related task
Hello world/Text
|
#R
|
R
|
library(RGtk2) # bindings to Gtk
w <- gtkWindowNew()
l <- gtkLabelNew("Goodbye, World!")
w$add(l)
|
http://rosettacode.org/wiki/Hello_world/Graphical
|
Hello world/Graphical
|
Task
Display the string Goodbye, World! on a GUI object (alert box, plain window, text area, etc.).
Related task
Hello world/Text
|
#Racket
|
Racket
|
#lang racket/gui
(require racket/gui/base)
; Make a frame by instantiating the frame% class
(define frame (new frame% [label "Goodbye, World!"]))
; Make a static text message in the frame
(define msg (new message% [parent frame]
[label "No events so far..."]))
; Make a button in the frame
(new button% [parent frame]
[label "Click Me"]
; Callback procedure for a button click:
(callback (lambda (button event)
(send msg set-label "Button click"))))
; Show the frame by calling its show method
(send frame show #t)
|
http://rosettacode.org/wiki/Gray_code
|
Gray code
|
Gray code
Karnaugh maps
Create functions to encode a number to and decode a number from Gray code.
Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary).
There are many possible Gray codes. The following encodes what is called "binary reflected Gray code."
Encoding (MSB is bit 0, b is binary, g is Gray code):
if b[i-1] = 1
g[i] = not b[i]
else
g[i] = b[i]
Or:
g = b xor (b logically right shifted 1 time)
Decoding (MSB is bit 0, b is binary, g is Gray code):
b[0] = g[0]
for other bits:
b[i] = g[i] xor b[i-1]
Reference
Converting Between Gray and Binary Codes. It includes step-by-step animations.
|
#Phix
|
Phix
|
with javascript_semantics
function gray_encode(integer n)
return xor_bits(n,floor(n/2))
end function
function gray_decode(integer n)
integer r = 0
while n>0 do
r = xor_bits(r,n)
n = floor(n/2)
end while
return r
end function
integer e,d
puts(1," N Binary Gray Decoded\n"&
"== ===== ===== =======\n")
for i=0 to 31 do
e = gray_encode(i)
d = gray_decode(e)
printf(1,"%2d %05b %05b %2d\n",{i,i,e,d})
end for
|
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!
|
#C.23
|
C#
|
static void Swap<T>(ref T a, ref T b)
{
T temp = a;
a = b;
b = temp;
}
|
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.
|
#Common_Lisp
|
Common Lisp
|
(max 1 2 3 4)
(reduce #'max values) ; find max of a list
(loop for x in values
maximize x) ; alternative way to find max of a list
|
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.
|
#Bracmat
|
Bracmat
|
(gcd=a b.!arg:(?a.?b)&!b*den$(!a*!b^-1)^-1);
|
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).
|
#Cowgol
|
Cowgol
|
include "cowgol.coh";
# Generate the hailstone sequence for the given N and return the length.
# If a non-NULL pointer to a buffer is given, then store the sequence there.
sub hailstone(n: uint32, buf: [uint32]): (len: uint32) is
len := 0;
loop
if buf != 0 as [uint32] then
[buf] := n;
buf := @next buf;
end if;
len := len + 1;
if n == 1 then
break;
elseif n & 1 == 0 then
n := n / 2;
else
n := 3*n + 1;
end if;
end loop;
end sub;
# Generate hailstone sequence for 27
var h27: uint32[113];
var h27len := hailstone(27, &h27[0]);
# Print information about it
print("The hailstone sequence for 27 has ");
print_i32(h27len);
print(" elements.\nThe first 4 elements are:");
var n: @indexof h27 := 0;
while n < 4 loop
print_char(' ');
print_i32(h27[n]);
n := n + 1;
end loop;
print(", and the last 4 elements are:");
n := h27len as @indexof h27 - 4;
while n as uint32 < h27len loop
print_char(' ');
print_i32(h27[n]);
n := n + 1;
end loop
print(".\n");
# Find longest hailstone sequence < 100,000
var i: uint32 := 1;
var max_i := i;
var len: uint32 := 0;
var max_len := len;
while i < 100000 loop
len := hailstone(i, 0 as [uint32]);
if len > max_len then
max_i := i;
max_len := len;
end if;
i := i + 1;
end loop;
print_i32(max_i);
print(" has the longest hailstone sequence < 100000: ");
print_i32(max_len);
print_nl();
|
http://rosettacode.org/wiki/Hamming_numbers
|
Hamming numbers
|
Hamming numbers are numbers of the form
H = 2i × 3j × 5k
where
i, j, k ≥ 0
Hamming numbers are also known as ugly numbers and also 5-smooth numbers (numbers whose prime divisors are less or equal to 5).
Task
Generate the sequence of Hamming numbers, in increasing order. In particular:
Show the first twenty Hamming numbers.
Show the 1691st Hamming number (the last one below 231).
Show the one millionth Hamming number (if the language – or a convenient library – supports arbitrary-precision integers).
Related tasks
Humble numbers
N-smooth numbers
References
Wikipedia entry: Hamming numbers (this link is re-directed to Regular number).
Wikipedia entry: Smooth number
OEIS entry: A051037 5-smooth or Hamming numbers
Hamming problem from Dr. Dobb's CodeTalk (dead link as of Sep 2011; parts of the thread here and here).
|
#M2000_Interpreter
|
M2000 Interpreter
|
Module hamming_long {
function hamming(l as long, &h(),&last()) {
l=if(l<1->1&, l)
long oldlen=len(h())
if oldlen<l then dim h(l) else =h(l-1): exit
def long i, j, k, n, m, x2, x3, x5, ll
stock last(0) out x2,x3,x5,i,j,k
n=oldlen : ll=l-1
{ m=x2
if m>x3 then m=x3
if m>x5 then m=x5
h(n)=m
if n>=1690 then =h(n):break
if m=x2 then i++:x2=2&*h(i)
if m=x3 then j++:x3=3&*h(j)
if m=x5 then k++:x5=5&*h(k)
if n<ll then n++: loop
}
stock last(0) in x2,x3,x5,i,j,k
=h(ll)
}
dim h(1)=1&, last()
def long i
const nl$={
}
document doc$
last()=(2&,3&,5&,0&,0&,0&)
for i=1 to 20
Doc$=format$("{0::-10} {1::-10}", i, hamming(i,&h(), &last()))+nl$
next i
i=1691
Doc$=format$("{0::-10} {1::-10}", i, hamming(i,&h(), &last()))+nl$
print #-2,Doc$
clipboard Doc$
}
hamming_long
|
http://rosettacode.org/wiki/Guess_the_number
|
Guess the number
|
Task
Write a program where the program chooses a number between 1 and 10.
A player is then prompted to enter a guess. If the player guesses wrong, then the prompt appears again until the guess is correct.
When the player has made a successful guess the computer will issue a "Well guessed!" message, and the program exits.
A conditional loop may be used to repeat the guessing until the user is correct.
Related tasks
Bulls and cows
Bulls and cows/Player
Guess the number/With Feedback
Mastermind
|
#Picat
|
Picat
|
go =>
N = random(1,10),
do print("Guess a number: ")
while (read_int() != N),
println("Well guessed!").
|
http://rosettacode.org/wiki/Guess_the_number
|
Guess the number
|
Task
Write a program where the program chooses a number between 1 and 10.
A player is then prompted to enter a guess. If the player guesses wrong, then the prompt appears again until the guess is correct.
When the player has made a successful guess the computer will issue a "Well guessed!" message, and the program exits.
A conditional loop may be used to repeat the guessing until the user is correct.
Related tasks
Bulls and cows
Bulls and cows/Player
Guess the number/With Feedback
Mastermind
|
#PicoLisp
|
PicoLisp
|
(de guessTheNumber ()
(let Number (rand 1 9)
(loop
(prin "Guess the number: ")
(T (= Number (read))
(prinl "Well guessed!") )
(prinl "Sorry, this was wrong") ) ) )
|
http://rosettacode.org/wiki/Greatest_subsequential_sum
|
Greatest subsequential sum
|
Task
Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one.
An empty subsequence is considered to have the sum of 0; thus if all elements are negative, the result must be the empty sequence.
|
#PureBasic
|
PureBasic
|
If OpenConsole()
Define s$, a, b, p1, p2, sum, max, dm=(?EndOfMyData-?MyData)
Dim Seq.i(dm/SizeOf(Integer))
CopyMemory(?MyData,@seq(),dm)
For a=0 To ArraySize(seq())
sum=0
For b=a To ArraySize(seq())
sum+seq(b)
If sum>max
max=sum
p1=a
p2=b
EndIf
Next
Next
For a=p1 To p2
s$+str(seq(a))
If a<p2
s$+"+"
EndIf
Next
PrintN(s$+" = "+str(max))
Print("Press ENTER to quit"): Input()
CloseConsole()
EndIf
DataSection
MyData:
Data.i -1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1
EndOfMyData:
EndDataSection
|
http://rosettacode.org/wiki/Guess_the_number/With_feedback
|
Guess the number/With feedback
|
Task
Write a game (computer program) that follows the following rules:
The computer chooses a number between given set limits.
The player is asked for repeated guesses until the the target number is guessed correctly
At each guess, the computer responds with whether the guess is:
higher than the target,
equal to the target,
less than the target, or
the input was inappropriate.
Related task
Guess the number/With Feedback (Player)
|
#Lambdatalk
|
Lambdatalk
|
{def game
{def game.rec // recursive part
{lambda {:n :l :h}
{let { {:n :n} {:l :l} {:h :h} // :n, :l, :h redefined
{:g {round {/ {+ :l :h} 2}}}} // :g is the middle
{if {< :g :n}
then {br}:g too low!
{game.rec :n {+ :g 1} :h} // do it again higher
else {if {> :g :n}
then {br}:g too high!
{game.rec :n :l {- :g 1}} // do it again lower
else {br}{b :g Got it!} }} }}} // bingo!
{lambda {:n}
{let { {:n :n} // :n redefined
{:N {floor {* :n {random}}}}} // compute a random number
Find {b :N} between 0 and :n {game.rec :N 0 :n}
}}}
{game {pow 2 32}} // 2**32 = 4294967296
|
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
|
#Logo
|
Logo
|
to sum_of_square_digits :number
output (apply "sum (map [[d] d*d] ` :number))
end
to is_happy? :number [:seen []]
output cond [
[ [:number = 1] "true ]
[ [member? :number :seen] "false ]
[ else (is_happy? (sum_of_square_digits :number) (lput :number :seen))]
]
end
to n_happy :count [:start 1] [:result []]
output cond [
[ [:count <= 0] :result ]
[ [is_happy? :start]
(n_happy (:count-1) (:start+1) (lput :start :result)) ]
[ else
(n_happy :count (:start+1) :result) ]
]
end
print n_happy 8
bye
|
http://rosettacode.org/wiki/Haversine_formula
|
Haversine formula
|
This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The haversine formula is an equation important in navigation, giving great-circle distances between two points on a sphere from their longitudes and latitudes.
It is a special case of a more general formula in spherical trigonometry, the law of haversines, relating the sides and angles of spherical "triangles".
Task
Implement a great-circle distance function, or use a library function,
to show the great-circle distance between:
Nashville International Airport (BNA) in Nashville, TN, USA, which is:
N 36°7.2', W 86°40.2' (36.12, -86.67) -and-
Los Angeles International Airport (LAX) in Los Angeles, CA, USA, which is:
N 33°56.4', W 118°24.0' (33.94, -118.40)
User Kaimbridge clarified on the Talk page:
-- 6371.0 km is the authalic radius based on/extracted from surface area;
-- 6372.8 km is an approximation of the radius of the average circumference
(i.e., the average great-elliptic or great-circle radius), where the
boundaries are the meridian (6367.45 km) and the equator (6378.14 km).
Using either of these values results, of course, in differing distances:
6371.0 km -> 2886.44444283798329974715782394574671655 km;
6372.8 km -> 2887.25995060711033944886005029688505340 km;
(results extended for accuracy check: Given that the radii are only
approximations anyways, .01' ≈ 1.0621333 km and .001" ≈ .00177 km,
practical precision required is certainly no greater than about
.0000001——i.e., .1 mm!)
As distances are segments of great circles/circumferences, it is
recommended that the latter value (r = 6372.8 km) be used (which
most of the given solutions have already adopted, anyways).
Most of the examples below adopted Kaimbridge's recommended value of
6372.8 km for the earth radius. However, the derivation of this
ellipsoidal quadratic mean radius
is wrong (the averaging over azimuth is biased). When applying these
examples in real applications, it is better to use the
mean earth radius,
6371 km. This value is recommended by the International Union of
Geodesy and Geophysics and it minimizes the RMS relative error between the
great circle and geodesic distance.
|
#XPL0
|
XPL0
|
include c:\cxpl\codes; \intrinsic 'code' declarations
func real Haversine(Ang);
real Ang;
return (1.0-Cos(Ang)) / 2.0;
func real Dist(Lat1, Lat2, Lon1, Lon2); \Great circle distance
real Lat1, Lat2, Lon1, Lon2;
def R = 6372.8; \average radius of Earth (km)
return 2.0*R * ASin( sqrt( Haversine(Lat2-Lat1) +
Cos(Lat1)*Cos(Lat2)*Haversine(Lon2-Lon1) ));
def D2R = 3.141592654/180.0; \degrees to radians
RlOut(0, Dist(36.12*D2R, 33.94*D2R, -86.67*D2R, -118.40*D2R ));
|
http://rosettacode.org/wiki/Haversine_formula
|
Haversine formula
|
This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The haversine formula is an equation important in navigation, giving great-circle distances between two points on a sphere from their longitudes and latitudes.
It is a special case of a more general formula in spherical trigonometry, the law of haversines, relating the sides and angles of spherical "triangles".
Task
Implement a great-circle distance function, or use a library function,
to show the great-circle distance between:
Nashville International Airport (BNA) in Nashville, TN, USA, which is:
N 36°7.2', W 86°40.2' (36.12, -86.67) -and-
Los Angeles International Airport (LAX) in Los Angeles, CA, USA, which is:
N 33°56.4', W 118°24.0' (33.94, -118.40)
User Kaimbridge clarified on the Talk page:
-- 6371.0 km is the authalic radius based on/extracted from surface area;
-- 6372.8 km is an approximation of the radius of the average circumference
(i.e., the average great-elliptic or great-circle radius), where the
boundaries are the meridian (6367.45 km) and the equator (6378.14 km).
Using either of these values results, of course, in differing distances:
6371.0 km -> 2886.44444283798329974715782394574671655 km;
6372.8 km -> 2887.25995060711033944886005029688505340 km;
(results extended for accuracy check: Given that the radii are only
approximations anyways, .01' ≈ 1.0621333 km and .001" ≈ .00177 km,
practical precision required is certainly no greater than about
.0000001——i.e., .1 mm!)
As distances are segments of great circles/circumferences, it is
recommended that the latter value (r = 6372.8 km) be used (which
most of the given solutions have already adopted, anyways).
Most of the examples below adopted Kaimbridge's recommended value of
6372.8 km for the earth radius. However, the derivation of this
ellipsoidal quadratic mean radius
is wrong (the averaging over azimuth is biased). When applying these
examples in real applications, it is better to use the
mean earth radius,
6371 km. This value is recommended by the International Union of
Geodesy and Geophysics and it minimizes the RMS relative error between the
great circle and geodesic distance.
|
#XQuery
|
XQuery
|
declare namespace xsd = "http://www.w3.org/2001/XMLSchema";
declare namespace math = "http://www.w3.org/2005/xpath-functions/math";
declare function local:haversine($lat1 as xsd:float, $lon1 as xsd:float, $lat2 as xsd:float, $lon2 as xsd:float)
as xsd:float
{
let $dlat := ($lat2 - $lat1) * math:pi() div 180
let $dlon := ($lon2 - $lon1) * math:pi() div 180
let $rlat1 := $lat1 * math:pi() div 180
let $rlat2 := $lat2 * math:pi() div 180
let $a := math:sin($dlat div 2) * math:sin($dlat div 2) + math:sin($dlon div 2) * math:sin($dlon div 2) * math:cos($rlat1) * math:cos($rlat2)
let $c := 2 * math:atan2(math:sqrt($a), math:sqrt(1-$a))
return xsd:float($c * 6371.0)
};
local:haversine(36.12, -86.67, 33.94, -118.4)
|
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
|
#Inform_6
|
Inform 6
|
[Main;
print "Hello world!^";
];
|
http://rosettacode.org/wiki/Harshad_or_Niven_series
|
Harshad or Niven series
|
The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits.
For example, 42 is a Harshad number as 42 is divisible by (4 + 2) without remainder.
Assume that the series is defined as the numbers in increasing order.
Task
The task is to create a function/method/procedure to generate successive members of the Harshad sequence.
Use it to:
list the first 20 members of the sequence, and
list the first Harshad number greater than 1000.
Show your output here.
Related task
Increasing gaps between consecutive Niven numbers
See also
OEIS: A005349
|
#XPL0
|
XPL0
|
include c:\cxpl\codes; \intrinsic 'code' declarations
int H, C, N, S; \Harshad number, Counter, Number, Sum
[H:= 1; C:= 0;
loop [N:= H; S:= 0; \sum digits
repeat N:= N/10;
S:= S + rem(0);
until N = 0;
if rem(H/S) = 0 then \Harshad no.is evenly divisible by sum of digits
[if C < 20 then [IntOut(0, H); ChOut(0, ^ ); C:= C+1];
if H > 1000 then [IntOut(0, H); CrLf(0); quit];
];
H:= H+1;
];
]
|
http://rosettacode.org/wiki/Hello_world/Graphical
|
Hello world/Graphical
|
Task
Display the string Goodbye, World! on a GUI object (alert box, plain window, text area, etc.).
Related task
Hello world/Text
|
#Raku
|
Raku
|
use GTK::Simple;
use GTK::Simple::App;
my GTK::Simple::App $app .= new;
$app.border-width = 20;
$app.set-content( GTK::Simple::Label.new(text => "Goodbye, World!") );
$app.run;
|
http://rosettacode.org/wiki/Hello_world/Graphical
|
Hello world/Graphical
|
Task
Display the string Goodbye, World! on a GUI object (alert box, plain window, text area, etc.).
Related task
Hello world/Text
|
#RapidQ
|
RapidQ
|
MessageBox("Goodbye, World!", "RapidQ example", 0)
|
http://rosettacode.org/wiki/Gray_code
|
Gray code
|
Gray code
Karnaugh maps
Create functions to encode a number to and decode a number from Gray code.
Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary).
There are many possible Gray codes. The following encodes what is called "binary reflected Gray code."
Encoding (MSB is bit 0, b is binary, g is Gray code):
if b[i-1] = 1
g[i] = not b[i]
else
g[i] = b[i]
Or:
g = b xor (b logically right shifted 1 time)
Decoding (MSB is bit 0, b is binary, g is Gray code):
b[0] = g[0]
for other bits:
b[i] = g[i] xor b[i-1]
Reference
Converting Between Gray and Binary Codes. It includes step-by-step animations.
|
#PHP
|
PHP
|
<?php
/**
* @author Elad Yosifon
*/
/**
* @param int $binary
* @return int
*/
function gray_encode($binary){
return $binary ^ ($binary >> 1);
}
/**
* @param int $gray
* @return int
*/
function gray_decode($gray){
$binary = $gray;
while($gray >>= 1) $binary ^= $gray;
return $binary;
}
for($i=0;$i<32;$i++){
$gray_encoded = gray_encode($i);
printf("%2d : %05b => %05b => %05b : %2d \n",$i, $i, $gray_encoded, $gray_encoded, gray_decode($gray_encoded));
}
|
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!
|
#C.2B.2B
|
C++
|
template<typename T> void swap(T& left, T& right)
{
T tmp(left);
left = right;
right = tmp;
}
|
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.
|
#Component_Pascal
|
Component Pascal
|
MODULE Operations;
IMPORT StdLog,Args,Strings;
PROCEDURE Max(s: ARRAY OF INTEGER): INTEGER;
VAR
i: INTEGER;
max: INTEGER;
BEGIN
max := MIN(INTEGER);
FOR i := 0 TO LEN(s) - 1 DO
max := MAX(max,s[i]);
END;
RETURN max
END Max;
PROCEDURE DoMax*;
VAR
sq: POINTER TO ARRAY OF INTEGER;
p: Args.Params;
i,n,done: INTEGER;
BEGIN
Args.Get(p);
IF p.argc > 0 THEN
NEW(sq,p.argc);
FOR i := 0 TO p.argc - 1 DO
Strings.StringToInt(p.args[i],n,done);
sq[i] := n
END;
StdLog.String("max:> ");StdLog.Int(Max(sq));StdLog.Ln
END
END DoMax;
END Operations.
|
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.
|
#C
|
C
|
int
gcd_iter(int u, int v) {
if (u < 0) u = -u;
if (v < 0) v = -v;
if (v) while ((u %= v) && (v %= u));
return (u + v);
}
|
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).
|
#Crystal
|
Crystal
|
def hailstone(n)
seq = [n]
until n == 1
n = n.even? ? n // 2 : n * 3 + 1
seq << n
end
seq
end
max_len = (1...100_000).max_by{|n| hailstone(n).size }
max = hailstone(max_len)
puts ([max_len, max.size, max.max, max.first(4), max.last(4)])
# => [77031, 351, 21933016, [77031, 231094, 115547, 346642], [8, 4, 2, 1]]
twenty_seven = hailstone(27)
puts ([twenty_seven.size, twenty_seven.first(4), max.last(4)])
# => [112, [27, 82, 41, 124], [8, 4, 2, 1]]
|
http://rosettacode.org/wiki/Hamming_numbers
|
Hamming numbers
|
Hamming numbers are numbers of the form
H = 2i × 3j × 5k
where
i, j, k ≥ 0
Hamming numbers are also known as ugly numbers and also 5-smooth numbers (numbers whose prime divisors are less or equal to 5).
Task
Generate the sequence of Hamming numbers, in increasing order. In particular:
Show the first twenty Hamming numbers.
Show the 1691st Hamming number (the last one below 231).
Show the one millionth Hamming number (if the language – or a convenient library – supports arbitrary-precision integers).
Related tasks
Humble numbers
N-smooth numbers
References
Wikipedia entry: Hamming numbers (this link is re-directed to Regular number).
Wikipedia entry: Smooth number
OEIS entry: A051037 5-smooth or Hamming numbers
Hamming problem from Dr. Dobb's CodeTalk (dead link as of Sep 2011; parts of the thread here and here).
|
#Mathematica_.2F_Wolfram_Language
|
Mathematica / Wolfram Language
|
HammingList[N_] := Module[{A, B, C}, {A, B, C} = (N^(1/3))*{2.8054745679851933, 1.7700573778298891, 1.2082521307023026} - {1, 1, 1};
Take[ Sort@Flatten@Table[ 2^x * 3^y * 5^z ,
{x, 0, A}, {y, 0, (-B/A)*x + B}, {z, 0, C - (C/A)*x - (C/B)*y}], N]];
|
http://rosettacode.org/wiki/Guess_the_number
|
Guess the number
|
Task
Write a program where the program chooses a number between 1 and 10.
A player is then prompted to enter a guess. If the player guesses wrong, then the prompt appears again until the guess is correct.
When the player has made a successful guess the computer will issue a "Well guessed!" message, and the program exits.
A conditional loop may be used to repeat the guessing until the user is correct.
Related tasks
Bulls and cows
Bulls and cows/Player
Guess the number/With Feedback
Mastermind
|
#Plain_English
|
Plain English
|
To run:
Start up.
Play guess the number.
Wait for the escape key.
Shut down.
To play guess the number:
Pick a secret number between 1 and 10.
Write "I picked a secret number between 1 and 10." to the console.
Loop.
Write "What is your guess? " to the console without advancing.
Read a number from the console.
If the number is the secret number, break.
Repeat.
Write "Well guessed!" to the console.
|
http://rosettacode.org/wiki/Guess_the_number
|
Guess the number
|
Task
Write a program where the program chooses a number between 1 and 10.
A player is then prompted to enter a guess. If the player guesses wrong, then the prompt appears again until the guess is correct.
When the player has made a successful guess the computer will issue a "Well guessed!" message, and the program exits.
A conditional loop may be used to repeat the guessing until the user is correct.
Related tasks
Bulls and cows
Bulls and cows/Player
Guess the number/With Feedback
Mastermind
|
#Plain_TeX
|
Plain TeX
|
\newlinechar`\^^J
\edef\tagetnumber{\number\numexpr1+\pdfuniformdeviate9}%
\message{^^JI'm thinking of a number between 1 and 10, try to guess it!}%
\newif\ifnotguessed
\notguessedtrue
\loop
\message{^^J^^JYour try: }\read -1 to \useranswer
\ifnum\useranswer=\tagetnumber\relax
\message{You win!^^J}\notguessedfalse
\else
\message{No, it's another number, try again...}%
\fi
\ifnotguessed
\repeat
\bye
|
http://rosettacode.org/wiki/Greatest_subsequential_sum
|
Greatest subsequential sum
|
Task
Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one.
An empty subsequence is considered to have the sum of 0; thus if all elements are negative, the result must be the empty sequence.
|
#Python
|
Python
|
def maxsubseq(seq):
return max((seq[begin:end] for begin in xrange(len(seq)+1)
for end in xrange(begin, len(seq)+1)),
key=sum)
|
http://rosettacode.org/wiki/Greatest_subsequential_sum
|
Greatest subsequential sum
|
Task
Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one.
An empty subsequence is considered to have the sum of 0; thus if all elements are negative, the result must be the empty sequence.
|
#R
|
R
|
max.subseq <- function(x) {
cumulative <- cumsum(x)
min.cumulative.so.far <- Reduce(min, cumulative, accumulate=TRUE)
end <- which.max(cumulative-min.cumulative.so.far)
begin <- which.min(c(0, cumulative[1:end]))
if (end >= begin) x[begin:end] else x[c()]
}
|
http://rosettacode.org/wiki/Guess_the_number/With_feedback
|
Guess the number/With feedback
|
Task
Write a game (computer program) that follows the following rules:
The computer chooses a number between given set limits.
The player is asked for repeated guesses until the the target number is guessed correctly
At each guess, the computer responds with whether the guess is:
higher than the target,
equal to the target,
less than the target, or
the input was inappropriate.
Related task
Guess the number/With Feedback (Player)
|
#Lasso
|
Lasso
|
#!/usr/bin/lasso9
local(
lower = integer_random(10, 1),
higher = integer_random(100, 20),
number = integer_random(#higher, #lower),
status = false,
guess
)
// prompt for a number
stdout('Guess a number: ')
while(not #status) => {
#guess = null
// the following bits wait until the terminal gives you back a line of input
while(not #guess or #guess -> size == 0) => {
#guess = file_stdin -> readSomeBytes(1024, 1000)
}
#guess = integer(#guess)
if(not (range(#guess, #lower, #higher) == #guess)) => {
stdout('Input not of correct type or range. Guess a number: ')
else(#guess > #number)
stdout('That was to high, try again! ')
else(#guess < #number)
stdout('That was to low, try again! ')
else(#guess == #number)
stdout('Well guessed!')
#status = true
}
}
|
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
|
#LOLCODE
|
LOLCODE
|
OBTW
Happy Numbers Rosetta Code task in LOLCODE
Requires 1.3 for BUKKIT availability
TLDR
HAI 1.3
CAN HAS STDIO?
BTW Simple list implementation.
BTW Used for the list of numbers already seen in IZHAPPY
BTW Create a list
HOW IZ I MAEKLIST
I HAS A LIST ITZ A BUKKIT
LIST HAS A LENGTH ITZ 0
FOUND YR LIST
IF U SAY SO
BTW Append an item to list
HOW IZ I PUTIN YR LIST AN YR ITEM
LIST HAS A SRS LIST'Z LENGTH ITZ ITEM
LIST'Z LENGTH R SUM OF LIST'Z LENGTH AN 1
IF U SAY SO
BTW Check for presence of an item in the list
HOW IZ I DUZLISTHAS YR HAYSTACK AN YR NEEDLE
IM IN YR BARN UPPIN YR INDEX WILE DIFFRINT INDEX AN HAYSTACK'Z LENGTH
I HAS A ITEM ITZ HAYSTACK'Z SRS INDEX
BOTH SAEM ITEM AN NEEDLE
O RLY?
YA RLY
FOUND YR WIN
OIC
IM OUTTA YR BARN
FOUND YR FAIL
IF U SAY SO
BTW Calculate the next number using the happy formula
HOW IZ I HAPPYSTEP YR NUM
I HAS A NEXT ITZ 0
IM IN YR LOOP
BOTH SAEM NUM AN 0
O RLY?
YA RLY
GTFO
OIC
I HAS A DIGIT ITZ MOD OF NUM AN 10
NUM R QUOSHUNT OF NUM AN 10
I HAS A SQUARE ITZ PRODUKT OF DIGIT AN DIGIT
NEXT R SUM OF NEXT AN SQUARE
IM OUTTA YR LOOP
FOUND YR NEXT
IF U SAY SO
BTW Check to see if a number is happy
HOW IZ I IZHAPPY YR NUM
I HAS A SEENIT ITZ I IZ MAEKLIST MKAY
IM IN YR LOOP
BOTH SAEM NUM AN 1
O RLY?
YA RLY
FOUND YR WIN
OIC
I IZ DUZLISTHAS YR SEENIT AN YR NUM MKAY
O RLY?
YA RLY
FOUND YR FAIL
OIC
I IZ PUTIN YR SEENIT AN YR NUM MKAY
NUM R I IZ HAPPYSTEP YR NUM MKAY
IM OUTTA YR LOOP
IF U SAY SO
BTW Print out the first 8 happy numbers
I HAS A KOUNT ITZ 0
IM IN YR LOOP UPPIN YR NUM WILE DIFFRINT KOUNT AN 8
I IZ IZHAPPY YR NUM MKAY
O RLY?
YA RLY
KOUNT R SUM OF KOUNT AN 1
VISIBLE NUM
OIC
IM OUTTA YR LOOP
KTHXBYE
|
http://rosettacode.org/wiki/Haversine_formula
|
Haversine formula
|
This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The haversine formula is an equation important in navigation, giving great-circle distances between two points on a sphere from their longitudes and latitudes.
It is a special case of a more general formula in spherical trigonometry, the law of haversines, relating the sides and angles of spherical "triangles".
Task
Implement a great-circle distance function, or use a library function,
to show the great-circle distance between:
Nashville International Airport (BNA) in Nashville, TN, USA, which is:
N 36°7.2', W 86°40.2' (36.12, -86.67) -and-
Los Angeles International Airport (LAX) in Los Angeles, CA, USA, which is:
N 33°56.4', W 118°24.0' (33.94, -118.40)
User Kaimbridge clarified on the Talk page:
-- 6371.0 km is the authalic radius based on/extracted from surface area;
-- 6372.8 km is an approximation of the radius of the average circumference
(i.e., the average great-elliptic or great-circle radius), where the
boundaries are the meridian (6367.45 km) and the equator (6378.14 km).
Using either of these values results, of course, in differing distances:
6371.0 km -> 2886.44444283798329974715782394574671655 km;
6372.8 km -> 2887.25995060711033944886005029688505340 km;
(results extended for accuracy check: Given that the radii are only
approximations anyways, .01' ≈ 1.0621333 km and .001" ≈ .00177 km,
practical precision required is certainly no greater than about
.0000001——i.e., .1 mm!)
As distances are segments of great circles/circumferences, it is
recommended that the latter value (r = 6372.8 km) be used (which
most of the given solutions have already adopted, anyways).
Most of the examples below adopted Kaimbridge's recommended value of
6372.8 km for the earth radius. However, the derivation of this
ellipsoidal quadratic mean radius
is wrong (the averaging over azimuth is biased). When applying these
examples in real applications, it is better to use the
mean earth radius,
6371 km. This value is recommended by the International Union of
Geodesy and Geophysics and it minimizes the RMS relative error between the
great circle and geodesic distance.
|
#Yabasic
|
Yabasic
|
//pi está predefinido en Yabasic
deg2rad = pi / 180 // define grados a radianes 0.01745..
radioTierra = 6372.8 // radio de la tierra en km
sub Haversine(lat1, long1, lat2, long2 , radio)
d_long = deg2rad * (long1 - long2)
theta1 = deg2rad * lat1
theta2 = deg2rad * lat2
dx = cos(d_long) * cos(theta1) - cos(theta2)
dy = sin(d_long) * cos(theta1)
dz = sin(theta1) - sin(theta2)
return asin(sqr(dx*dx + dy*dy + dz*dz) / 2) * radio * 2
end sub
print " Distancia de Haversine entre BNA y LAX = ", Haversine(36.12, -86.67, 33.94, -118.4, radioTierra), " km"
end
|
http://rosettacode.org/wiki/Haversine_formula
|
Haversine formula
|
This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The haversine formula is an equation important in navigation, giving great-circle distances between two points on a sphere from their longitudes and latitudes.
It is a special case of a more general formula in spherical trigonometry, the law of haversines, relating the sides and angles of spherical "triangles".
Task
Implement a great-circle distance function, or use a library function,
to show the great-circle distance between:
Nashville International Airport (BNA) in Nashville, TN, USA, which is:
N 36°7.2', W 86°40.2' (36.12, -86.67) -and-
Los Angeles International Airport (LAX) in Los Angeles, CA, USA, which is:
N 33°56.4', W 118°24.0' (33.94, -118.40)
User Kaimbridge clarified on the Talk page:
-- 6371.0 km is the authalic radius based on/extracted from surface area;
-- 6372.8 km is an approximation of the radius of the average circumference
(i.e., the average great-elliptic or great-circle radius), where the
boundaries are the meridian (6367.45 km) and the equator (6378.14 km).
Using either of these values results, of course, in differing distances:
6371.0 km -> 2886.44444283798329974715782394574671655 km;
6372.8 km -> 2887.25995060711033944886005029688505340 km;
(results extended for accuracy check: Given that the radii are only
approximations anyways, .01' ≈ 1.0621333 km and .001" ≈ .00177 km,
practical precision required is certainly no greater than about
.0000001——i.e., .1 mm!)
As distances are segments of great circles/circumferences, it is
recommended that the latter value (r = 6372.8 km) be used (which
most of the given solutions have already adopted, anyways).
Most of the examples below adopted Kaimbridge's recommended value of
6372.8 km for the earth radius. However, the derivation of this
ellipsoidal quadratic mean radius
is wrong (the averaging over azimuth is biased). When applying these
examples in real applications, it is better to use the
mean earth radius,
6371 km. This value is recommended by the International Union of
Geodesy and Geophysics and it minimizes the RMS relative error between the
great circle and geodesic distance.
|
#zkl
|
zkl
|
haversine(36.12, -86.67, 33.94, -118.40).println();
fcn haversine(Lat1, Long1, Lat2, Long2){
const R = 6372.8; // In kilometers;
Diff_Lat := (Lat2 - Lat1) .toRad();
Diff_Long := (Long2 - Long1).toRad();
NLat := Lat1.toRad();
NLong := Lat2.toRad();
A := (Diff_Lat/2) .sin().pow(2) +
(Diff_Long/2).sin().pow(2) *
NLat.cos() * NLong.cos();
C := 2.0 * A.sqrt().asin();
R*C;
}
|
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
|
#Inko
|
Inko
|
import std::stdio::stdout
stdout.print('Hello, world!')
|
http://rosettacode.org/wiki/Harshad_or_Niven_series
|
Harshad or Niven series
|
The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits.
For example, 42 is a Harshad number as 42 is divisible by (4 + 2) without remainder.
Assume that the series is defined as the numbers in increasing order.
Task
The task is to create a function/method/procedure to generate successive members of the Harshad sequence.
Use it to:
list the first 20 members of the sequence, and
list the first Harshad number greater than 1000.
Show your output here.
Related task
Increasing gaps between consecutive Niven numbers
See also
OEIS: A005349
|
#Yabasic
|
Yabasic
|
sub sumDigits(n)
if n < 0 then return 0 : endif
local sum
while n > 0
sum = sum + mod(n, 10)
n = int(n / 10)
wend
return sum
end sub
sub isHarshad(n)
return mod(n, sumDigits(n)) = 0
end sub
print "Los primeros 20 numeros de Harshad o Niven son:"
contar = 0
i = 1
repeat
if isHarshad(i) then
print i, " ",
contar = contar + 1
end if
i = i + 1
until contar = 20
print : print
print "El primero de esos numeros por encima de 1000 es:"
i = 1001
do
if isHarshad(i) then
print i, " "
break
end if
i = i + 1
loop
print
end
|
http://rosettacode.org/wiki/Hello_world/Graphical
|
Hello world/Graphical
|
Task
Display the string Goodbye, World! on a GUI object (alert box, plain window, text area, etc.).
Related task
Hello world/Text
|
#Rascal
|
Rascal
|
import vis::Figure;
import vis::Render;
public void GoodbyeWorld() =
render(box(text("Goodbye World")));
|
http://rosettacode.org/wiki/Hello_world/Graphical
|
Hello world/Graphical
|
Task
Display the string Goodbye, World! on a GUI object (alert box, plain window, text area, etc.).
Related task
Hello world/Text
|
#REALbasic
|
REALbasic
|
MsgBox("Goodbye, World!")
|
http://rosettacode.org/wiki/Gray_code
|
Gray code
|
Gray code
Karnaugh maps
Create functions to encode a number to and decode a number from Gray code.
Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary).
There are many possible Gray codes. The following encodes what is called "binary reflected Gray code."
Encoding (MSB is bit 0, b is binary, g is Gray code):
if b[i-1] = 1
g[i] = not b[i]
else
g[i] = b[i]
Or:
g = b xor (b logically right shifted 1 time)
Decoding (MSB is bit 0, b is binary, g is Gray code):
b[0] = g[0]
for other bits:
b[i] = g[i] xor b[i-1]
Reference
Converting Between Gray and Binary Codes. It includes step-by-step animations.
|
#Picat
|
Picat
|
go =>
foreach(I in 0..2**5-1)
G = gray_encode1(I),
E = gray_decode1(G),
printf("%2d %6w %2d %6w %6w %2d\n",I,I.to_binary_string,
G, G.to_binary_string,
E.to_binary_string, E)
end,
nl,
println("Checking 2**1300:"),
N2=2**1300,
G2=gray_encode1(N2),
E2=gray_decode1(G2),
% println(g2=G2),
% println(e2=E2),
println(check=cond(N2==E2,same,not_same)),
nl.
gray_encode1(N) = N ^ (N >> 1).
gray_decode1(N) = P =>
P = N,
N := N >> 1,
while (N != 0)
P := P ^ N,
N := N >> 1
end.
|
http://rosettacode.org/wiki/Gray_code
|
Gray code
|
Gray code
Karnaugh maps
Create functions to encode a number to and decode a number from Gray code.
Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary).
There are many possible Gray codes. The following encodes what is called "binary reflected Gray code."
Encoding (MSB is bit 0, b is binary, g is Gray code):
if b[i-1] = 1
g[i] = not b[i]
else
g[i] = b[i]
Or:
g = b xor (b logically right shifted 1 time)
Decoding (MSB is bit 0, b is binary, g is Gray code):
b[0] = g[0]
for other bits:
b[i] = g[i] xor b[i-1]
Reference
Converting Between Gray and Binary Codes. It includes step-by-step animations.
|
#PicoLisp
|
PicoLisp
|
(de grayEncode (N)
(bin (x| N (>> 1 N))) )
(de grayDecode (G)
(bin
(pack
(let X 0
(mapcar
'((C) (setq X (x| X (format C))))
(chop G) ) ) ) ) )
|
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!
|
#Chapel
|
Chapel
|
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.
|
#Crystal
|
Crystal
|
values.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.
|
#C.23
|
C#
|
static void Main()
{
Console.WriteLine("GCD of {0} and {1} is {2}", 1, 1, gcd(1, 1));
Console.WriteLine("GCD of {0} and {1} is {2}", 1, 10, gcd(1, 10));
Console.WriteLine("GCD of {0} and {1} is {2}", 10, 100, gcd(10, 100));
Console.WriteLine("GCD of {0} and {1} is {2}", 5, 50, gcd(5, 50));
Console.WriteLine("GCD of {0} and {1} is {2}", 8, 24, gcd(8, 24));
Console.WriteLine("GCD of {0} and {1} is {2}", 36, 17, gcd(36, 17));
Console.WriteLine("GCD of {0} and {1} is {2}", 36, 18, gcd(36, 18));
Console.WriteLine("GCD of {0} and {1} is {2}", 36, 19, gcd(36, 19));
for (int x = 1; x < 36; x++)
{
Console.WriteLine("GCD of {0} and {1} is {2}", 36, x, gcd(36, x));
}
Console.Read();
}
/// <summary>
/// Greatest Common Denominator using Euclidian Algorithm
/// </summary>
static int gcd(int a, int b)
{
while (b != 0) b = a % (a = b);
return 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).
|
#D
|
D
|
import std.stdio, std.algorithm, std.range, std.typecons;
auto hailstone(uint n) pure nothrow {
auto result = [n];
while (n != 1) {
n = (n & 1) ? (n * 3 + 1) : (n / 2);
result ~= n;
}
return result;
}
void main() {
enum M = 27;
immutable h = M.hailstone;
writeln("hailstone(", M, ")= ", h[0 .. 4], " ... " , h[$ - 4 .. $]);
writeln("Length hailstone(", M, ")= ", h.length);
enum N = 100_000;
immutable p = iota(1, N)
.map!(i => tuple(i.hailstone.length, i))
.reduce!max;
writeln("Longest sequence in [1,", N, "]= ",p[1]," with len ",p[0]);
}
|
http://rosettacode.org/wiki/Hamming_numbers
|
Hamming numbers
|
Hamming numbers are numbers of the form
H = 2i × 3j × 5k
where
i, j, k ≥ 0
Hamming numbers are also known as ugly numbers and also 5-smooth numbers (numbers whose prime divisors are less or equal to 5).
Task
Generate the sequence of Hamming numbers, in increasing order. In particular:
Show the first twenty Hamming numbers.
Show the 1691st Hamming number (the last one below 231).
Show the one millionth Hamming number (if the language – or a convenient library – supports arbitrary-precision integers).
Related tasks
Humble numbers
N-smooth numbers
References
Wikipedia entry: Hamming numbers (this link is re-directed to Regular number).
Wikipedia entry: Smooth number
OEIS entry: A051037 5-smooth or Hamming numbers
Hamming problem from Dr. Dobb's CodeTalk (dead link as of Sep 2011; parts of the thread here and here).
|
#MATLAB_.2F_Octave
|
MATLAB / Octave
|
n = 40;
powers_2 = 2.^[0:n-1];
powers_3 = 3.^[0:n-1];
powers_5 = 5.^[0:n-1];
matrix = powers_2' * powers_3;
powers_23 = sort(reshape(matrix,n*n,1));
matrix = powers_23 * powers_5;
powers_235 = sort(reshape(matrix,n*n*n,1));
%
% Remove the integer overflow values.
%
powers_235 = powers_235(powers_235 > 0);
disp(powers_235(1:20))
disp(powers_235(1691))
|
http://rosettacode.org/wiki/Guess_the_number
|
Guess the number
|
Task
Write a program where the program chooses a number between 1 and 10.
A player is then prompted to enter a guess. If the player guesses wrong, then the prompt appears again until the guess is correct.
When the player has made a successful guess the computer will issue a "Well guessed!" message, and the program exits.
A conditional loop may be used to repeat the guessing until the user is correct.
Related tasks
Bulls and cows
Bulls and cows/Player
Guess the number/With Feedback
Mastermind
|
#PowerShell
|
PowerShell
|
Function GuessNumber($Guess)
{
$Number = Get-Random -min 1 -max 11
Write-Host "What number between 1 and 10 am I thinking of?"
Do
{
Write-Warning "Try again!"
$Guess = Read-Host "What's the number?"
}
While ($Number -ne $Guess)
Write-Host "Well done! You successfully guessed the number $Guess."
}
|
http://rosettacode.org/wiki/Guess_the_number
|
Guess the number
|
Task
Write a program where the program chooses a number between 1 and 10.
A player is then prompted to enter a guess. If the player guesses wrong, then the prompt appears again until the guess is correct.
When the player has made a successful guess the computer will issue a "Well guessed!" message, and the program exits.
A conditional loop may be used to repeat the guessing until the user is correct.
Related tasks
Bulls and cows
Bulls and cows/Player
Guess the number/With Feedback
Mastermind
|
#ProDOS
|
ProDOS
|
:a
editvar /modify /value=-random-= <10
editvar /newvar /value=-random- /title=a
editvar /newvar /value=b /userinput=1 /title=Guess a number:
if -b- /hasvalue=-a- printline You guessed correctly! else printline Your guess was wrong & goto :a
|
http://rosettacode.org/wiki/Greatest_subsequential_sum
|
Greatest subsequential sum
|
Task
Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one.
An empty subsequence is considered to have the sum of 0; thus if all elements are negative, the result must be the empty sequence.
|
#Racket
|
Racket
|
(define (max-subseq l)
(define-values (_ result _1 max-sum)
(for/fold ([seq '()] [max-seq '()] [sum 0] [max-sum 0])
([i l])
(cond [(> (+ sum i) max-sum)
(values (cons i seq) (cons i seq) (+ sum i) (+ sum i))]
[(< (+ sum i) 0)
(values '() max-seq 0 max-sum)]
[else
(values (cons i seq) max-seq (+ sum i) max-sum)])))
(values (reverse result) max-sum))
|
http://rosettacode.org/wiki/Greatest_subsequential_sum
|
Greatest subsequential sum
|
Task
Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one.
An empty subsequence is considered to have the sum of 0; thus if all elements are negative, the result must be the empty sequence.
|
#Raku
|
Raku
|
sub max-subseq (*@a) {
my ($start, $end, $sum, $maxsum) = -1, -1, 0, 0;
for @a.kv -> $i, $x {
$sum += $x;
if $maxsum < $sum {
($maxsum, $end) = $sum, $i;
}
elsif $sum < 0 {
($sum, $start) = 0, $i;
}
}
return @a[$start ^.. $end];
}
|
http://rosettacode.org/wiki/Guess_the_number/With_feedback
|
Guess the number/With feedback
|
Task
Write a game (computer program) that follows the following rules:
The computer chooses a number between given set limits.
The player is asked for repeated guesses until the the target number is guessed correctly
At each guess, the computer responds with whether the guess is:
higher than the target,
equal to the target,
less than the target, or
the input was inappropriate.
Related task
Guess the number/With Feedback (Player)
|
#LFE
|
LFE
|
(defmodule guessing-game
(export (main 0)))
(defun get-player-guess ()
(let (((tuple 'ok (list guessed)) (: io fread '"Guess number: " '"~d")))
guessed))
(defun check-guess (answer guessed)
(cond
((== answer guessed)
(: io format '"Well-guessed!!~n"))
((/= answer guessed)
(if (> answer guessed) (: io format '"Your guess is too low.~n"))
(if (< answer guessed) (: io format '"Your guess is too high.~n"))
(check-guess answer (get-player-guess)))))
(defun main ()
(: io format '"Guess the number I have chosen, between 1 and 10.~n")
(check-guess
(: random uniform 10)
(get-player-guess)))
|
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
|
#Lua
|
Lua
|
function digits(n)
if n > 0 then return n % 10, digits(math.floor(n/10)) end
end
function sumsq(a, ...)
return a and a ^ 2 + sumsq(...) or 0
end
local happy = setmetatable({true, false, false, false}, {
__index = function(self, n)
self[n] = self[sumsq(digits(n))]
return self[n]
end } )
i, j = 0, 1
repeat
i, j = happy[j] and (print(j) or i+1) or i, j + 1
until i == 8
|
http://rosettacode.org/wiki/Haversine_formula
|
Haversine formula
|
This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The haversine formula is an equation important in navigation, giving great-circle distances between two points on a sphere from their longitudes and latitudes.
It is a special case of a more general formula in spherical trigonometry, the law of haversines, relating the sides and angles of spherical "triangles".
Task
Implement a great-circle distance function, or use a library function,
to show the great-circle distance between:
Nashville International Airport (BNA) in Nashville, TN, USA, which is:
N 36°7.2', W 86°40.2' (36.12, -86.67) -and-
Los Angeles International Airport (LAX) in Los Angeles, CA, USA, which is:
N 33°56.4', W 118°24.0' (33.94, -118.40)
User Kaimbridge clarified on the Talk page:
-- 6371.0 km is the authalic radius based on/extracted from surface area;
-- 6372.8 km is an approximation of the radius of the average circumference
(i.e., the average great-elliptic or great-circle radius), where the
boundaries are the meridian (6367.45 km) and the equator (6378.14 km).
Using either of these values results, of course, in differing distances:
6371.0 km -> 2886.44444283798329974715782394574671655 km;
6372.8 km -> 2887.25995060711033944886005029688505340 km;
(results extended for accuracy check: Given that the radii are only
approximations anyways, .01' ≈ 1.0621333 km and .001" ≈ .00177 km,
practical precision required is certainly no greater than about
.0000001——i.e., .1 mm!)
As distances are segments of great circles/circumferences, it is
recommended that the latter value (r = 6372.8 km) be used (which
most of the given solutions have already adopted, anyways).
Most of the examples below adopted Kaimbridge's recommended value of
6372.8 km for the earth radius. However, the derivation of this
ellipsoidal quadratic mean radius
is wrong (the averaging over azimuth is biased). When applying these
examples in real applications, it is better to use the
mean earth radius,
6371 km. This value is recommended by the International Union of
Geodesy and Geophysics and it minimizes the RMS relative error between the
great circle and geodesic distance.
|
#ZX_Spectrum_Basic
|
ZX Spectrum Basic
|
10 LET diam=2*6372.8
20 LET Lg1m2=FN r((-86.67)-(-118.4))
30 LET Lt1=FN r(36.12)
40 LET Lt2=FN r(33.94)
50 LET dz=SIN (Lt1)-SIN (Lt2)
60 LET dx=COS (Lg1m2)*COS (Lt1)-COS (Lt2)
70 LET dy=SIN (Lg1m2)*COS (Lt1)
80 LET hDist=ASN ((dx*dx+dy*dy+dz*dz)^0.5/2)*diam
90 PRINT "Haversine distance: ";hDist;" km."
100 STOP
1000 DEF FN r(a)=a*0.017453293: REM convert degree to radians
|
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
|
#Intercal
|
Intercal
|
DO ,1 <- #13
PLEASE DO ,1 SUB #1 <- #238
DO ,1 SUB #2 <- #108
DO ,1 SUB #3 <- #112
DO ,1 SUB #4 <- #0
DO ,1 SUB #5 <- #64
DO ,1 SUB #6 <- #194
PLEASE DO ,1 SUB #7 <- #48
DO ,1 SUB #8 <- #26
DO ,1 SUB #9 <- #244
PLEASE DO ,1 SUB #10 <- #168
DO ,1 SUB #11 <- #24
DO ,1 SUB #12 <- #16
DO ,1 SUB #13 <- #162
PLEASE READ OUT ,1
PLEASE GIVE UP
|
http://rosettacode.org/wiki/Harshad_or_Niven_series
|
Harshad or Niven series
|
The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits.
For example, 42 is a Harshad number as 42 is divisible by (4 + 2) without remainder.
Assume that the series is defined as the numbers in increasing order.
Task
The task is to create a function/method/procedure to generate successive members of the Harshad sequence.
Use it to:
list the first 20 members of the sequence, and
list the first Harshad number greater than 1000.
Show your output here.
Related task
Increasing gaps between consecutive Niven numbers
See also
OEIS: A005349
|
#zkl
|
zkl
|
fcn harshad(n){ 0==n%(n.split().sum(0)) }
[1..].tweak(fcn(n){ if(not harshad(n)) return(Void.Skip); n })
.walk(20).println();
[1..].filter(20,harshad).println();
[1001..].filter1(harshad).println();
|
http://rosettacode.org/wiki/Hello_world/Graphical
|
Hello world/Graphical
|
Task
Display the string Goodbye, World! on a GUI object (alert box, plain window, text area, etc.).
Related task
Hello world/Text
|
#REBOL
|
REBOL
|
alert "Goodbye, World!"
|
http://rosettacode.org/wiki/Hello_world/Graphical
|
Hello world/Graphical
|
Task
Display the string Goodbye, World! on a GUI object (alert box, plain window, text area, etc.).
Related task
Hello world/Text
|
#Red
|
Red
|
>> view [ text "Hello World !"]
|
http://rosettacode.org/wiki/Gray_code
|
Gray code
|
Gray code
Karnaugh maps
Create functions to encode a number to and decode a number from Gray code.
Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary).
There are many possible Gray codes. The following encodes what is called "binary reflected Gray code."
Encoding (MSB is bit 0, b is binary, g is Gray code):
if b[i-1] = 1
g[i] = not b[i]
else
g[i] = b[i]
Or:
g = b xor (b logically right shifted 1 time)
Decoding (MSB is bit 0, b is binary, g is Gray code):
b[0] = g[0]
for other bits:
b[i] = g[i] xor b[i-1]
Reference
Converting Between Gray and Binary Codes. It includes step-by-step animations.
|
#PL.2FI
|
PL/I
|
(stringrange, stringsize):
Gray_code: procedure options (main); /* 15 November 2013 */
declare (bin(0:31), g(0:31), b2(0:31)) bit (5);
declare (c, carry) bit (1);
declare (i, j) fixed binary (7);
bin(0) = '00000'b;
do i = 0 to 31;
if i > 0 then
do;
carry = '1'b;
bin(i) = bin(i-1);
do j = 5 to 1 by -1;
c = substr(bin(i), j, 1) & carry;
substr(bin(i), j, 1) = substr(bin(i), j, 1) ^ carry;
carry = c;
end;
end;
g(i) = bin(i) ^ '0'b || substr(bin(i), 1, 4);
end;
do i = 0 to 31;
substr(b2(i), 1, 1) = substr(g(i), 1, 1);
do j = 2 to 5;
substr(b2(i), j, 1) = substr(g(i), j, 1) ^ substr(bin(i), j-1, 1);
end;
end;
do i = 0 to 31;
put skip edit (i, bin(i), g(i), b2(i)) (f(2), 3(x(1), b));
end;
end Gray_code;
|
http://rosettacode.org/wiki/Gray_code
|
Gray code
|
Gray code
Karnaugh maps
Create functions to encode a number to and decode a number from Gray code.
Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary).
There are many possible Gray codes. The following encodes what is called "binary reflected Gray code."
Encoding (MSB is bit 0, b is binary, g is Gray code):
if b[i-1] = 1
g[i] = not b[i]
else
g[i] = b[i]
Or:
g = b xor (b logically right shifted 1 time)
Decoding (MSB is bit 0, b is binary, g is Gray code):
b[0] = g[0]
for other bits:
b[i] = g[i] xor b[i-1]
Reference
Converting Between Gray and Binary Codes. It includes step-by-step animations.
|
#PowerBASIC
|
PowerBASIC
|
function gray%(byval n%)
gray%=n% xor (n%\2)
end function
function igray%(byval n%)
r%=0
while n%>0
r%=r% xor n%
shift right n%,1
wend
igray%=r%
end function
print " N GRAY INV"
for n%=0 to 31
g%=gray%(n%)
print bin$(n%);" ";bin$(g%);" ";bin$(igray%(g%))
next
|
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!
|
#Clojure
|
Clojure
|
(defn swap [pair] (reverse pair)) ; returns a list
(defn swap [[a b]] '(b a)) ; returns a list
(defn swap [[a b]] [b a]) ; returns a vector
|
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.
|
#D
|
D
|
void main()
{
import std.algorithm.searching : maxElement;
import std.stdio : writeln;
[9, 4, 3, 8, 5].maxElement.writeln;
}
|
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.
|
#C.2B.2B
|
C++
|
#include <iostream>
#include <numeric>
int main() {
std::cout << "The greatest common divisor of 12 and 18 is " << std::gcd(12, 18) << " !\n";
}
|
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).
|
#Dart
|
Dart
|
List<int> hailstone(int n) {
if(n<=0) {
throw new IllegalArgumentException("start value must be >=1)");
}
Queue<int> seq=new Queue<int>();
seq.add(n);
while(n!=1) {
n=n%2==0?(n/2).toInt():3*n+1;
seq.add(n);
}
return new List<int>.from(seq);
}
// apparently List is missing toString()
String iterableToString(Iterable seq) {
String str="[";
Iterator i=seq.iterator();
while(i.hasNext()) {
str+=i.next();
if(i.hasNext()) {
str+=",";
}
}
return str+"]";
}
main() {
for(int i=1;i<=10;i++) {
print("h($i)="+iterableToString(hailstone(i)));
}
List<int> h27=hailstone(27);
List<int> first4=h27.getRange(0,4);
print("first 4 elements of h(27): "+iterableToString(first4));
Expect.listEquals([27,82,41,124],first4);
List<int> last4=h27.getRange(h27.length-4,4);
print("last 4 elements of h(27): "+iterableToString(last4));
Expect.listEquals([8,4,2,1],last4);
print("length of sequence h(27): "+h27.length);
Expect.equals(112,h27.length);
int seq,max=0;
for(int i=1;i<=100000;i++) {
List<int> h=hailstone(i);
if(h.length>max) {
max=h.length;
seq=i;
}
}
print("up to 100000 the sequence h($seq) has the largest length ($max)");
}
|
http://rosettacode.org/wiki/Hamming_numbers
|
Hamming numbers
|
Hamming numbers are numbers of the form
H = 2i × 3j × 5k
where
i, j, k ≥ 0
Hamming numbers are also known as ugly numbers and also 5-smooth numbers (numbers whose prime divisors are less or equal to 5).
Task
Generate the sequence of Hamming numbers, in increasing order. In particular:
Show the first twenty Hamming numbers.
Show the 1691st Hamming number (the last one below 231).
Show the one millionth Hamming number (if the language – or a convenient library – supports arbitrary-precision integers).
Related tasks
Humble numbers
N-smooth numbers
References
Wikipedia entry: Hamming numbers (this link is re-directed to Regular number).
Wikipedia entry: Smooth number
OEIS entry: A051037 5-smooth or Hamming numbers
Hamming problem from Dr. Dobb's CodeTalk (dead link as of Sep 2011; parts of the thread here and here).
|
#MUMPS
|
MUMPS
|
Hamming(n) New count,ok,next,number,which
For which=2,3,5 Set number=1
For count=1:1:n Do
. Set ok=0 Set:count<21 ok=1 Set:count=1691 ok=1 Set:count=n ok=1
. Write:ok !,$Justify(count,5),": ",number
. For which=2,3,5 Set next(number*which)=which
. Set number=$Order(next(""))
. Kill next(number)
. Quit
Quit
Do Hamming(2000)
1: 1
2: 2
3: 3
4: 4
5: 5
6: 6
7: 8
8: 9
9: 10
10: 12
11: 15
12: 16
13: 18
14: 20
15: 24
16: 25
17: 27
18: 30
19: 32
20: 36
1691: 2125764000
2000: 8062156800
|
http://rosettacode.org/wiki/Guess_the_number
|
Guess the number
|
Task
Write a program where the program chooses a number between 1 and 10.
A player is then prompted to enter a guess. If the player guesses wrong, then the prompt appears again until the guess is correct.
When the player has made a successful guess the computer will issue a "Well guessed!" message, and the program exits.
A conditional loop may be used to repeat the guessing until the user is correct.
Related tasks
Bulls and cows
Bulls and cows/Player
Guess the number/With Feedback
Mastermind
|
#Prolog
|
Prolog
|
main :-
random_between(1, 10, N),
repeat,
prompt1('Guess the number: '),
read(N),
writeln('Well guessed!'),
!.
|
http://rosettacode.org/wiki/Guess_the_number
|
Guess the number
|
Task
Write a program where the program chooses a number between 1 and 10.
A player is then prompted to enter a guess. If the player guesses wrong, then the prompt appears again until the guess is correct.
When the player has made a successful guess the computer will issue a "Well guessed!" message, and the program exits.
A conditional loop may be used to repeat the guessing until the user is correct.
Related tasks
Bulls and cows
Bulls and cows/Player
Guess the number/With Feedback
Mastermind
|
#PureBasic
|
PureBasic
|
If OpenConsole()
Define TheNumber=Random(9)+1
PrintN("I've picked a number from 1 to 10." + #CRLF$)
Repeat
Print("Guess the number: ")
Until TheNumber=Val(Input())
PrintN("Well guessed!")
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf
|
http://rosettacode.org/wiki/Greatest_subsequential_sum
|
Greatest subsequential sum
|
Task
Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one.
An empty subsequence is considered to have the sum of 0; thus if all elements are negative, the result must be the empty sequence.
|
#Raven
|
Raven
|
[ -1 -2 3 5 6 -2 -1 4 -4 2 -1 ] as $seq
1 31 shl as $max
0 $seq length 1 range each as $i
0 as $sum
$i $seq length 1 range each as $j
$seq $j get $sum + as $sum
$sum $max > if
$sum as $max
$i as $i1
$j as $j1
"Sum: " print
$i1 $j1 1 range each
#dup "$seq[%d]\n" print
$seq swap get "%d," print
$max $seq $j1 get "%d = %d\n" print
|
http://rosettacode.org/wiki/Greatest_subsequential_sum
|
Greatest subsequential sum
|
Task
Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one.
An empty subsequence is considered to have the sum of 0; thus if all elements are negative, the result must be the empty sequence.
|
#REXX
|
REXX
|
/*REXX program finds and displays the longest greatest continuous subsequence sum. */
parse arg @; w= words(@); p= w + 1 /*get arg list; number words in list. */
say 'words='w " list="@ /*show number words & LIST to terminal,*/
do #=1 for w; @.#= word(@, #); end /*build an array for faster processing.*/
L=0; sum= 0 /* [↓] process the list of numbers. */
do j=1 for w /*select one number at a time from list*/
do k=j to w; _= k-j+1; s= @.j /* [↓] process a sub─list of numbers. */
do m=j+1 to k; s= s + @.m; end /*m*/
if (s==sum & _>L) | s>sum then do; sum= s; p= j; L= _; end
end /*k*/ /* [↑] chose the longest greatest sum.*/
end /*j*/
say
$= subword(@,p,L); if $=='' then $= "[NULL]" /*Englishize the null (value). */
say 'sum='sum/1 " sequence="$ /*stick a fork in it, we're all done. */
|
http://rosettacode.org/wiki/Guess_the_number/With_feedback
|
Guess the number/With feedback
|
Task
Write a game (computer program) that follows the following rules:
The computer chooses a number between given set limits.
The player is asked for repeated guesses until the the target number is guessed correctly
At each guess, the computer responds with whether the guess is:
higher than the target,
equal to the target,
less than the target, or
the input was inappropriate.
Related task
Guess the number/With Feedback (Player)
|
#Liberty_BASIC
|
Liberty BASIC
|
[start]
target = int( rnd( 1) * 100) +1
while 1
do
input "Guess a whole number between 1 and 100. To finish, type 'exit' "; b$
if b$ ="exit" then print "Thank you for playing!": end
c = val( b$)
ok =( c =int( c)) and ( c >=1) and ( c <=100)
if ok =0 then notice "Invalid data. Integers 1 to 100 only."
loop until ok <>0
if c =target then print " You guessed correctly.": print: goto [start]
if c <target then print " Your guess was too low."
if c >target then print " Your guess was too high."
wend
|
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
|
#M2000_Interpreter
|
M2000 Interpreter
|
Function FactoryHappy {
sumOfSquares= lambda (n) ->{
k$=str$(abs(n),"")
Sum=0
For i=1 to len(k$)
sum+=val(mid$(k$,i,1))**2
Next i
=sum
}
IsHappy=Lambda sumOfSquares (n) ->{
Inventory sequence
While n<>1 {
Append sequence, n
n=sumOfSquares(n)
if exist(sequence, n) then =false : Break
}
=True
}
=Lambda IsHappy ->{
numleft=8
numToTest=1
While numleft {
if ishappy(numToTest) Then {
Print numToTest
numleft--
}
numToTest++
}
}
}
PrintHappy=factoryHappy()
Call PrintHappy()
|
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
|
#Integer_BASIC
|
Integer BASIC
|
10 PRINT "Hello world!"
20 END
|
http://rosettacode.org/wiki/Harshad_or_Niven_series
|
Harshad or Niven series
|
The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits.
For example, 42 is a Harshad number as 42 is divisible by (4 + 2) without remainder.
Assume that the series is defined as the numbers in increasing order.
Task
The task is to create a function/method/procedure to generate successive members of the Harshad sequence.
Use it to:
list the first 20 members of the sequence, and
list the first Harshad number greater than 1000.
Show your output here.
Related task
Increasing gaps between consecutive Niven numbers
See also
OEIS: A005349
|
#ZX_Spectrum_Basic
|
ZX Spectrum Basic
|
10 LET k=0: LET n=0
20 IF k=20 THEN GO TO 60
30 LET n=n+1: GO SUB 1000
40 IF isHarshad THEN PRINT n;" ";: LET k=k+1
50 GO TO 20
60 LET n=1001
70 GO SUB 1000: IF NOT isHarshad THEN LET n=n+1: GO TO 70
80 PRINT '"First Harshad number larger than 1000 is ";n
90 STOP
1000 REM is Harshad?
1010 LET s=0: LET n$=STR$ n
1020 FOR i=1 TO LEN n$
1030 LET s=s+VAL n$(i)
1040 NEXT i
1050 LET isHarshad=NOT FN m(n,s)
1060 RETURN
1100 DEF FN m(a,b)=a-INT (a/b)*b
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.