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/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).
|
#SQL
|
SQL
|
CREATE TEMPORARY TABLE factors(n INT);
INSERT INTO factors VALUES(2);
INSERT INTO factors VALUES(3);
INSERT INTO factors VALUES(5);
CREATE TEMPORARY TABLE hamming AS
WITH RECURSIVE ham AS (
SELECT 1 AS h
UNION
SELECT h*n x FROM ham JOIN factors ORDER BY x
LIMIT 1700
)
SELECT h FROM ham;
sqlite> SELECT h FROM hamming ORDER BY h LIMIT 20;
1
2
3
4
5
6
8
9
10
12
15
16
18
20
24
25
27
30
32
36
sqlite> SELECT h FROM hamming ORDER BY h LIMIT 1 OFFSET 1690;
2125764000
|
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)
|
#Racket
|
Racket
|
#lang racket
(define (guess-number min max)
(define target (+ min (random (- max min -1))))
(printf "I'm thinking of a number between ~a and ~a\n" min max)
(let loop ([prompt "Your guess"])
(printf "~a: " prompt)
(flush-output)
(define guess (read))
(define response
(cond [(not (exact-integer? guess)) "Please enter a valid integer"]
[(< guess target) "Too low"]
[(> guess target) "Too high"]
[else #f]))
(when response (printf "~a\n" response) (loop "Try again")))
(printf "Well guessed!\n"))
(guess-number 1 100)
|
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)
|
#Raku
|
Raku
|
my $maxnum = prompt("Hello, please give me an upper boundary: ");
until 0 < $maxnum < Inf {
say "Oops! The upper boundary should be > 0 and not Inf";
$maxnum = prompt("Please give me a valid upper boundary: ");
}
my $count = 0;
my $number = (1..$maxnum).pick;
say "I'm thinking of a number from 1 to $maxnum, try to guess it!";
repeat until my $guessed-right {
given prompt("Your guess: ") {
when /^[e|q]/ { say 'Goodbye.'; exit; }
when not 1 <= $_ <= $maxnum {
say "You really should give me a number from 1 to $maxnum."
}
$count++;
when $number { $guessed-right = True }
when $number < $_ { say "Sorry, my number is smaller." }
when $number > $_ { say "Sorry, my number is bigger." }
}
}
say "Great you guessed right after $count attempts!";
|
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
|
#PureBasic
|
PureBasic
|
#ToFind=8
#MaxTests=100
#True = 1: #False = 0
Declare is_happy(n)
If OpenConsole()
Define i=1,Happy
Repeat
If is_happy(i)
Happy+1
PrintN("#"+Str(Happy)+RSet(Str(i),3))
EndIf
i+1
Until Happy>=#ToFind
;
Print(#CRLF$+#CRLF$+"Press ENTER to exit"): Input()
CloseConsole()
EndIf
Procedure is_happy(n)
Protected i,j=n,dig,sum
Repeat
sum=0
While j
dig=j%10
j/10
sum+dig*dig
Wend
If sum=1: ProcedureReturn #True: EndIf
j=sum
i+1
Until i>#MaxTests
ProcedureReturn #False
EndProcedure
|
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
|
#Lang5
|
Lang5
|
"Hello world!\n" .
|
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!
|
#Go
|
Go
|
a, b = b, a
|
http://rosettacode.org/wiki/Greatest_element_of_a_list
|
Greatest element of a list
|
Task
Create a function that returns the maximum value in a provided set of values,
where the number of values may not be known until run-time.
|
#Icon_and_Unicon
|
Icon and Unicon
|
procedure main()
local l
l := [7,8,6,9,4,5,2,3,1]
write(max(l))
end
procedure max(l)
local max
max := l[1]
every max <:= !l
return max
end
|
http://rosettacode.org/wiki/Greatest_common_divisor
|
Greatest common divisor
|
Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related task
least common multiple.
See also
MathWorld entry: greatest common divisor.
Wikipedia entry: greatest common divisor.
|
#Free_Pascal
|
Free Pascal
|
' version 17-06-2015
' compile with: fbc -s console
Function gcd(x As ULongInt, y As ULongInt) As ULongInt
Dim As ULongInt t
While y
t = y
y = x Mod y
x = t
Wend
Return x
End Function
' ------=< MAIN >=------
Dim As ULongInt a = 111111111111111
Dim As ULongInt b = 11111
Print : Print "GCD(";a;", ";b;") = "; gcd(a, b)
Print : Print "GCD(";a;", 111) = "; gcd(a, 111)
' empty keyboard buffer
While InKey <> "" : Wend
Print : Print : Print "hit any key to end program"
Sleep
End
|
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).
|
#HicEst
|
HicEst
|
DIMENSION stones(1000)
H27 = hailstone(27)
ALIAS(stones,1, first4,4)
ALIAS(stones,H27-3, last4,4)
WRITE(ClipBoard, Name) H27, first4, "...", last4
longest_sequence = 0
DO try = 1, 1E5
elements = hailstone(try)
IF(elements >= longest_sequence) THEN
number = try
longest_sequence = elements
WRITE(StatusBar, Name) number, longest_sequence
ENDIF
ENDDO
WRITE(ClipBoard, Name) number, longest_sequence
END
FUNCTION hailstone( n )
USE : stones
stones(1) = n
DO i = 1, LEN(stones)
IF(stones(i) == 1) THEN
hailstone = i
RETURN
ELSEIF( MOD(stones(i),2) ) THEN
stones(i+1) = 3*stones(i) + 1
ELSE
stones(i+1) = stones(i) / 2
ENDIF
ENDDO
END
|
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).
|
#Tcl
|
Tcl
|
package require Tcl 8.6
# Simple helper: Tcl-style list "map"
proc map {varName list script} {
set l {}
upvar 1 $varName v
foreach v $list {lappend l [uplevel 1 $script]}
return $l
}
# The core of a coroutine to compute the product of a hamming sequence.
#
# Tricky bit: we don't automatically advance to the next value, and instead
# wait to be told that the value has been consumed (i.e., is the result of
# the [yield] operation).
proc ham {key multiplier} {
global hammingCache
set i 0
yield [info coroutine]
# Cannot use [foreach]; that would take a snapshot of the list in
# the hammingCache variable, so missing updates.
while 1 {
set n [expr {[lindex $hammingCache($key) $i] * $multiplier}]
# If the number selected was ours, we advance to compute the next
if {[yield $n] == $n} {
incr i
}
}
}
# This coroutine computes the hamming sequence given a list of multipliers.
# It uses the [ham] helper from above to generate indivdual multiplied
# sequences. The key into the cache is the list of multipliers.
#
# Note that it is advisable for the values to be all co-prime wrt each other.
proc hammingCore args {
global hammingCache
set hammingCache($args) 1
set hammers [map x $args {coroutine ham$x,$args ham $args $x}]
yield
while 1 {
set n [lindex $hammingCache($args) [incr i]-1]
lappend hammingCache($args) \
[tcl::mathfunc::min {*}[map h $hammers {$h $n}]]
yield $n
}
}
# Assemble the pieces so as to compute the classic hamming sequence.
coroutine hamming hammingCore 2 3 5
# Print the first 20 values of the sequence
for {set i 1} {$i <= 20} {incr i} {
puts [format "hamming\[%d\] = %d" $i [hamming]]
}
for {} {$i <= 1690} {incr i} {set h [hamming]}
puts "hamming{1690} = $h"
for {} {$i <= 1000000} {incr i} {set h [hamming]}
puts "hamming{1000000} = $h"
|
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)
|
#Retro
|
Retro
|
: high|low ( gn-g$ )
over > [ "high" ] [ "low" ] if ;
: checkGuess ( gn-gf || f )
2over = [ "You guessed correctly!\n" puts 2drop 0 ]
[ high|low "Sorry, your guess was too %s.\nTry again.\n" puts -1 ] if ;
: think ( -n )
random abs 100 mod 1+ ;
: guess ( - )
"I'm thinking of a number between 1 and 100.\n" puts
"Try to guess it!\n" puts
think [ getToken toNumber checkGuess ] while
"You got it!\n" puts ;
|
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)
|
#REXX
|
REXX
|
/*REXX program plays guess the number game with a human; the computer picks the number*/
low= 1 /*the lower range for the guessing game*/
high= 100 /* " upper " " " " " */
try= 0 /*the number of valid (guess) attempts.*/
r= random(low, high) /*get a random number (low ───► high).*/
lows= 'too_low too_small too_little below under underneath too_puny'
highs= 'too_high too_big too_much above over over_the_top too_huge'
erm= '***error***'
@gtn= "guess the number, it's between"
prompt= centre(@gtn low 'and' high '(inclusive) ───or─── Quit:', 79, "─")
/* [↓] BY 0 ─── used to LEAVE a loop*/
do ask=0 by 0; say; say prompt; say; pull g; g= space(g); say
do validate=0 by 0 /*DO index required; LEAVE instruction.*/
select
when g=='' then iterate ask
when abbrev('QUIT', g, 1) then exit /*what a whoos.*/
when words(g) \== 1 then say erm 'too many numbers entered:' g
when \datatype(g, 'N') then say erm g "isn't numeric"
when \datatype(g, 'W') then say erm g "isn't a whole number"
when g<low then say erm g 'is below the lower limit of' low
when g>high then say erm g 'is above the higher limit of' high
otherwise leave /*validate*/
end /*select*/
iterate ask
end /*validate*/
try= try + 1
if g=r then leave
if g>r then what= word(highs, random(1, words(highs) ) )
else what= word( lows, random(1, words( lows) ) )
say 'your guess of' g "is" translate(what, , "_").
end /*ask*/
/*stick a fork in it, we're all done. */
if try==1 then say 'Gadzooks!!! You guessed the number right away!'
else say 'Congratulations!, you guessed the number in ' try " tries."
|
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
|
#Python
|
Python
|
>>> def happy(n):
past = set()
while n != 1:
n = sum(int(i)**2 for i in str(n))
if n in past:
return False
past.add(n)
return True
>>> [x for x in xrange(500) if happy(x)][:8]
[1, 7, 10, 13, 19, 23, 28, 31]
|
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
|
#langur
|
langur
|
writeln "yo, peeps"
|
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!
|
#Gri
|
Gri
|
`Swap Vars &.a. &.b.'
{
new .temp.
.temp. = \.word2.
\.word2. = \.word3.
\.word3. = .temp.
delete .temp.
}
.foo. = 123
.bar. = 456
Swap Vars &.foo. &.bar.
show .foo. " " .bar.
# prints "456 123"
|
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.
|
#IS-BASIC
|
IS-BASIC
|
1000 DEF FINDMAX(REF ARR)
1010 LET MX=ARR(LBOUND(ARR))
1020 FOR I=LBOUND(ARR)+1 TO UBOUND(ARR)
1030 LET MX=MAX(MX,ARR(I))
1040 NEXT
1050 LET FINDMAX=MX
1060 END DEF
|
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.
|
#J
|
J
|
>./
|
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.
|
#FreeBASIC
|
FreeBASIC
|
' version 17-06-2015
' compile with: fbc -s console
Function gcd(x As ULongInt, y As ULongInt) As ULongInt
Dim As ULongInt t
While y
t = y
y = x Mod y
x = t
Wend
Return x
End Function
' ------=< MAIN >=------
Dim As ULongInt a = 111111111111111
Dim As ULongInt b = 11111
Print : Print "GCD(";a;", ";b;") = "; gcd(a, b)
Print : Print "GCD(";a;", 111) = "; gcd(a, 111)
' empty keyboard buffer
While InKey <> "" : Wend
Print : Print : Print "hit any key to end program"
Sleep
End
|
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).
|
#Icon_and_Unicon
|
Icon and Unicon
|
procedure hailstone(n)
while n > 1 do {
suspend n
n := if n%2 = 0 then n/2 else 3*n+1
}
suspend 1
end
|
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).
|
#uBasic.2F4tH
|
uBasic/4tH
|
For H = 1 To 20
Print "H("; H; ") = "; Func (_FnHamming(H))
Next
End
_FnHamming Param (1)
@(0) = 1
X = 2 : Y = 3 : Z = 5
I = 0 : J = 0 : K = 0
For N = 1 To a@ - 1
M = X
If M > Y Then M = Y
If M > Z Then M = Z
@(N) = M
If M = X Then I = I + 1 : X = 2 * @(I)
If M = Y Then J = J + 1 : Y = 3 * @(J)
If M = Z Then K = K + 1 : Z = 5 * @(K)
Next
Return (@(a@-1))
|
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)
|
#Ring
|
Ring
|
fr = 1 t0 = 10
while true
see "Hey There,
========================
I'm thinking of a number between " + fr + " and " + t0 + ", Can you guess it??
Guess :> "
give x
n = nrandom(fr,t0)
if x = n see "
Congratulations :D
*****************************************************
** Your guess was right You Are Genius :D **
*****************************************************
"
exit
else
see "Oops its not true, you were just few steps"
if x > n see " up :)" else see " down :)" ok
see copy(nl,3)
ok
end
func nRandom s,e
while true
d = random(e)
if d >= s return d ok
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)
|
#Ruby
|
Ruby
|
number = rand(1..10)
puts "Guess the number between 1 and 10"
loop do
begin
user_number = Integer(gets)
if user_number == number
puts "You guessed it."
break
elsif user_number > number
puts "Too high."
else
puts "Too low."
end
rescue ArgumentError
puts "Please enter an integer."
end
end
|
http://rosettacode.org/wiki/Happy_numbers
|
Happy numbers
|
From Wikipedia, the free encyclopedia:
A happy number is defined by the following process:
Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.
Those numbers for which this process end in 1 are happy numbers,
while those numbers that do not end in 1 are unhappy numbers.
Task
Find and print the first 8 happy numbers.
Display an example of your output here on this page.
See also
The OEIS entry: The happy numbers: A007770
The OEIS entry: The unhappy numbers; A031177
|
#Quackery
|
Quackery
|
[ 0 swap
[ 10 /mod 2 **
rot + swap
dup 0 = until ]
drop ] is digitsquare ( n --> n )
[ [ digitsquare
dup 1 != while
dup 42 != while
again ]
1 = ] is happy ( n --> b )
[ [] 1
[ dip
[ 2dup size > ]
swap while
dup happy if
[ tuck join swap ]
1+ again ]
drop nip ] is happies ( n --> [ )
8 happies echo
|
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
|
#Lasso
|
Lasso
|
'Hello world!'
|
http://rosettacode.org/wiki/Generic_swap
|
Generic swap
|
Task
Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types.
If your solution language is statically typed please describe the way your language provides genericity.
If variables are typed in the given language, it is permissible that the two variables be constrained to having a mutually compatible type, such that each is permitted to hold the value previously stored in the other without a type violation.
That is to say, solutions do not have to be capable of exchanging, say, a string and integer value, if the underlying storage locations are not attributed with types that permit such an exchange.
Generic swap is a task which brings together a few separate issues in programming language semantics.
Dynamically typed languages deal with values in a generic way quite readily, but do not necessarily make it easy to write a function to destructively swap two variables, because this requires indirection upon storage places or upon the syntax designating storage places.
Functional languages, whether static or dynamic, do not necessarily allow a destructive operation such as swapping two variables regardless of their generic capabilities.
Some static languages have difficulties with generic programming due to a lack of support for (Parametric Polymorphism).
Do your best!
|
#Groovy
|
Groovy
|
(a, b) = [b, a]
|
http://rosettacode.org/wiki/Greatest_element_of_a_list
|
Greatest element of a list
|
Task
Create a function that returns the maximum value in a provided set of values,
where the number of values may not be known until run-time.
|
#Janet
|
Janet
|
(def elems @[3 1 3 2])
# Use extreme function from stdlib with > function.
(extreme > elems)
# Unpack list as arguments to max function.
(max ;elems)
|
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.
|
#Java
|
Java
|
public static float max(float[] values) throws NoSuchElementException {
if (values.length == 0)
throw new NoSuchElementException();
float themax = values[0];
for (int idx = 1; idx < values.length; ++idx) {
if (values[idx] > themax)
themax = values[idx];
}
return themax;
}
|
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.
|
#Frege
|
Frege
|
module gcd.GCD where
pure native parseInt java.lang.Integer.parseInt :: String -> Int
gcd' a 0 = a
gcd' a b = gcd' b (a `mod` b)
main args = do
(a:b:_) = args
println $ gcd' (parseInt a) (parseInt b)
|
http://rosettacode.org/wiki/Hailstone_sequence
|
Hailstone sequence
|
The Hailstone sequence of numbers can be generated from a starting positive integer, n by:
If n is 1 then the sequence ends.
If n is even then the next n of the sequence = n/2
If n is odd then the next n of the sequence = (3 * n) + 1
The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates.
This sequence was named by Lothar Collatz in 1937 (or possibly in 1939), and is also known as (the):
hailstone sequence, hailstone numbers
3x + 2 mapping, 3n + 1 problem
Collatz sequence
Hasse's algorithm
Kakutani's problem
Syracuse algorithm, Syracuse problem
Thwaites conjecture
Ulam's problem
The hailstone sequence is also known as hailstone numbers (because the values are usually subject to multiple descents and ascents like hailstones in a cloud).
Task
Create a routine to generate the hailstone sequence for a number.
Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1
Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.
(But don't show the actual sequence!)
See also
xkcd (humourous).
The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).
The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).
|
#Inform_7
|
Inform 7
|
Home is a room.
To decide which list of numbers is the hailstone sequence for (N - number):
let result be a list of numbers;
add N to result;
while N is not 1:
if N is even, let N be N / 2;
otherwise let N be (3 * N) + 1;
add N to result;
decide on result.
Hailstone length cache relates various numbers to one number.
To decide which number is the hailstone sequence length for (N - number):
let ON be N;
let length so far be 0;
while N is not 1:
if N relates to a number by the hailstone length cache relation:
let result be length so far plus the number to which N relates by the hailstone length cache relation;
now the hailstone length cache relation relates ON to result;
decide on result;
if N is even, let N be N / 2;
otherwise let N be (3 * N) + 1;
increment length so far;
let result be length so far plus 1;
now the hailstone length cache relation relates ON to result;
decide on result.
To say first and last (N - number) entry/entries in (L - list of values of kind K):
let length be the number of entries in L;
if length <= N * 2:
say L;
else:
repeat with M running from 1 to N:
if M > 1, say ", ";
say entry M in L;
say " ... ";
repeat with M running from length - N + 1 to length:
say entry M in L;
if M < length, say ", ".
When play begins:
let H27 be the hailstone sequence for 27;
say "Hailstone sequence for 27 has [number of entries in H27] element[s]: [first and last 4 entries in H27].";
let best length be 0;
let best number be 0;
repeat with N running from 1 to 99999:
let L be the hailstone sequence length for N;
if L > best length:
let best length be L;
let best number be N;
say "The number under 100,000 with the longest hailstone sequence is [best number] with [best length] element[s].";
end the story.
|
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).
|
#UNIX_Shell
|
UNIX Shell
|
typeset -a hamming=(1)
function nextHamming {
typeset -Sa q2 q3 q5
integer h=${hamming[${#hamming[@]}-1]}
q2+=( $(( h*2 )) )
q3+=( $(( h*3 )) )
q5+=( $(( h*5 )) )
h=$( min3 ${q2[0]} ${q3[0]} ${q5[0]} )
(( ${q2[0]} == h )) && ashift q2 >/dev/null
(( ${q3[0]} == h )) && ashift q3 >/dev/null
(( ${q5[0]} == h )) && ashift q5 >/dev/null
hamming+=($h)
}
function ashift {
nameref ary=$1
print -- "${ary[0]}"
ary=( "${ary[@]:1}" )
}
function min3 {
if (( $1 < $2 )); then
(( $1 < $3 )) && print -- $1 || print -- $3
else
(( $2 < $3 )) && print -- $2 || print -- $3
fi
}
for ((i=1; i<=20; i++)); do
nextHamming
printf "%d\t%d\n" $i ${hamming[i-1]}
done
for ((; i<=1690; i++)); do nextHamming; done
nextHamming
printf "%d\t%d\n" $i ${hamming[i-1]}
print "elapsed: $SECONDS"
|
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)
|
#Rust
|
Rust
|
use rand::Rng;
use std::cmp::Ordering;
use std::io;
const LOWEST: u32 = 1;
const HIGHEST: u32 = 100;
fn main() {
let secret_number = rand::thread_rng().gen_range(1..101);
println!("I have chosen my number between {} and {}. Guess the number!", LOWEST, HIGHEST);
loop {
println!("Please input your guess.");
let mut guess = String::new();
io::stdin()
.read_line(&mut guess)
.expect("Failed to read line");
let guess: u32 = match guess.trim().parse() {
Ok(num) => num,
Err(_) => continue,
};
println!("You guessed: {}", guess);
match guess.cmp(&secret_number) {
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => {
println!("You win!");
break;
}
}
}
}
|
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)
|
#Scala
|
Scala
|
import java.util.Random
import java.util.Scanner
val scan = new Scanner(System.in)
val random = new Random
val (from , to) = (1, 100)
val randomNumber = random.nextInt(to - from + 1) + from
var guessedNumber = 0
printf("The number is between %d and %d.\n", from, to)
do {
print("Guess what the number is: ")
guessedNumber = scan.nextInt
if (guessedNumber > randomNumber) println("Your guess is too high!")
else if (guessedNumber < randomNumber) println("Your guess is too low!")
else println("You got it!")
} while (guessedNumber != randomNumber)
|
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
|
#R
|
R
|
is.happy <- function(n)
{
stopifnot(is.numeric(n) && length(n)==1)
getdigits <- function(n)
{
as.integer(unlist(strsplit(as.character(n), "")))
}
digits <- getdigits(n)
previous <- c()
repeat
{
sumsq <- sum(digits^2, na.rm=TRUE)
if(sumsq==1L)
{
happy <- TRUE
break
} else if(sumsq %in% previous)
{
happy <- FALSE
attr(happy, "cycle") <- previous
break
} else
{
previous <- c(previous, sumsq)
digits <- getdigits(sumsq)
}
}
happy
}
|
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
|
#LaTeX
|
LaTeX
|
\documentclass{minimal}
\begin{document}
Hello World!
\end{document}
|
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!
|
#Harbour
|
Harbour
|
PROCEDURE Swap( /*@*/v1, /*@*/v2 )
LOCAL xTmp
xTmp := v1
v1 := v2
v2 := xTmp
RETURN
|
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.
|
#JavaScript
|
JavaScript
|
Math.max.apply(null, [ 0, 1, 2, 5, 4 ]); // 5
|
http://rosettacode.org/wiki/Greatest_common_divisor
|
Greatest common divisor
|
Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related task
least common multiple.
See also
MathWorld entry: greatest common divisor.
Wikipedia entry: greatest common divisor.
|
#Frink
|
Frink
|
println[gcd[12345,98765]]
|
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.
|
#FunL
|
FunL
|
def
gcd( 0, 0 ) = error( 'integers.gcd: gcd( 0, 0 ) is undefined' )
gcd( a, b ) =
def
_gcd( a, 0 ) = a
_gcd( a, b ) = _gcd( b, a%b )
_gcd( abs(a), abs(b) )
|
http://rosettacode.org/wiki/Hailstone_sequence
|
Hailstone sequence
|
The Hailstone sequence of numbers can be generated from a starting positive integer, n by:
If n is 1 then the sequence ends.
If n is even then the next n of the sequence = n/2
If n is odd then the next n of the sequence = (3 * n) + 1
The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates.
This sequence was named by Lothar Collatz in 1937 (or possibly in 1939), and is also known as (the):
hailstone sequence, hailstone numbers
3x + 2 mapping, 3n + 1 problem
Collatz sequence
Hasse's algorithm
Kakutani's problem
Syracuse algorithm, Syracuse problem
Thwaites conjecture
Ulam's problem
The hailstone sequence is also known as hailstone numbers (because the values are usually subject to multiple descents and ascents like hailstones in a cloud).
Task
Create a routine to generate the hailstone sequence for a number.
Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1
Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.
(But don't show the actual sequence!)
See also
xkcd (humourous).
The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).
The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).
|
#Io
|
Io
|
makeItHail := method(n,
stones := list(n)
while (n != 1,
if(n isEven,
n = n / 2,
n = 3 * n + 1
)
stones append(n)
)
stones
)
out := makeItHail(27)
writeln("For the sequence beginning at 27, the number of elements generated is ", out size, ".")
write("The first four elements generated are ")
for(i, 0, 3,
write(out at(i), " ")
)
writeln(".")
write("The last four elements generated are ")
for(i, out size - 4, out size - 1,
write(out at(i), " ")
)
writeln(".")
numOfElems := 0
nn := 3
for(x, 3, 100000,
out = makeItHail(x)
if(out size > numOfElems,
numOfElems = out size
nn = x
)
)
writeln("For numbers less than or equal to 100,000, ", nn,
" has the longest sequence of ", numOfElems, " elements.")
|
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).
|
#Ursala
|
Ursala
|
#import std
#import nat
smooth"p" "n" = ~&z take/"n" nleq-< (rep(length "n") ^Ts/~& product*K0/"p") <1>
|
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)
|
#Scheme
|
Scheme
|
(define maximum 5)
(define minimum -5)
(define number (+ (random (- (+ maximum 1) minimum)) minimum))
(display "Pick a number from ")
(display minimum)
(display " through ")
(display maximum)
(display ".\n> ")
(do ((guess (read) (read))) ((eq? guess number))
(if (or (>= guess maximum) (< guess minimum))
(display "Out of range!\n> ")
(begin
(if (> guess number)
(display "Too high!\n> "))
(if (< guess number)
(display "Too low!\n> ")))))
(display "Correct!\n")
|
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
|
#Racket
|
Racket
|
#lang racket
(define (sum-of-squared-digits number (result 0))
(if (zero? number)
result
(sum-of-squared-digits (quotient number 10)
(+ result (expt (remainder number 10) 2)))))
(define (happy-number? number (seen null))
(define next (sum-of-squared-digits number))
(cond ((= 1 next)
#t)
((memq next seen)
#f)
(else
(happy-number? next (cons number seen)))))
(define (get-happys max)
(for/list ((x (in-range max))
#:when (happy-number? x))
x))
(display (take (get-happys 100) 8)) ;displays (1 7 10 13 19 23 28 31)
|
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
|
#Latitude
|
Latitude
|
putln "Hello world!".
|
http://rosettacode.org/wiki/Generic_swap
|
Generic swap
|
Task
Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types.
If your solution language is statically typed please describe the way your language provides genericity.
If variables are typed in the given language, it is permissible that the two variables be constrained to having a mutually compatible type, such that each is permitted to hold the value previously stored in the other without a type violation.
That is to say, solutions do not have to be capable of exchanging, say, a string and integer value, if the underlying storage locations are not attributed with types that permit such an exchange.
Generic swap is a task which brings together a few separate issues in programming language semantics.
Dynamically typed languages deal with values in a generic way quite readily, but do not necessarily make it easy to write a function to destructively swap two variables, because this requires indirection upon storage places or upon the syntax designating storage places.
Functional languages, whether static or dynamic, do not necessarily allow a destructive operation such as swapping two variables regardless of their generic capabilities.
Some static languages have difficulties with generic programming due to a lack of support for (Parametric Polymorphism).
Do your best!
|
#Haskell
|
Haskell
|
swap :: (a, b) -> (b, a)
swap (x, y) = (y, x)
|
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.
|
#jq
|
jq
|
[1, 3, 1.0] | max # => 3
[ {"a": 1}, {"a":3}, {"a":1.0}] | max # => {"a": 3}
|
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.
|
#Julia
|
Julia
|
julia> maximum([1,3,3,7])
7
julia> maximum([pi,e+2/5,cos(6)/5,sqrt(91/10)])
3.141592653589793
julia> maximum([1,6,Inf])
Inf
julia> maximum(Float64[])
maximum: argument is empty
at In[138]:1
in maximum at abstractarray.jl:1591
|
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.
|
#FutureBasic
|
FutureBasic
|
window 1, @"Greatest Common Divisor", (0,0,480,270)
local fn gcd( a as short, b as short ) as short
short result
if ( b != 0 )
result = fn gcd( b, a mod b)
else
result = abs(a)
end if
end fn = result
print fn gcd( 6, 9 )
HandleEvents
|
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.
|
#GAP
|
GAP
|
# Built-in
GcdInt(35, 42);
# 7
# Euclidean algorithm
GcdInteger := function(a, b)
local c;
a := AbsInt(a);
b := AbsInt(b);
while b > 0 do
c := a;
a := b;
b := RemInt(c, b);
od;
return a;
end;
GcdInteger(35, 42);
# 7
|
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).
|
#Ioke
|
Ioke
|
collatz = method(n,
n println
unless(n <= 1,
if(n even?, collatz(n / 2), collatz(n * 3 + 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).
|
#VBA
|
VBA
|
'RosettaCode Hamming numbers
'This is a well known hard problem in number theory:
'counting the number of lattice points in a
'n-dimensional tetrahedron, here n=3.
Public a As Double, b As Double, c As Double, d As Double
Public p As Double, q As Double, r As Double
Public cnt() As Integer 'stores the number of lattice points indexed on the exponents of 3 and 5
Public hn(2) As Integer 'stores the exponents of 2, 3 and 5
Public Declare Function GetTickCount Lib "kernel32.dll" () As Long
Private Function log10(x As Double) As Double
log10 = WorksheetFunction.log10(x)
End Function
Private Function pow(x As Variant, y As Variant) As Double
pow = WorksheetFunction.Power(x, y)
End Function
Private Sub init(N As Long)
'Computes a, b and c as the vertices
'(a,0,0), (0,b,0), (0,0,c) of a tetrahedron
'with apex (0,0,0) and volume N
'volume N=a*b*c/6
Dim k As Double
k = log10(2) * log10(3) * log10(5) * 6 * N
k = pow(k, 1 / 3)
a = k / log10(2)
b = k / log10(3)
c = k / log10(5)
p = -b * c
q = -a * c
r = -a * b
End Sub
Private Function x_given_y_z(y As Integer, z As Integer) As Double
x_given_y_z = -(q * y + r * z + a * b * c) / p
End Function
Private Function cmp(i As Integer, j As Integer, k As Integer, gn() As Integer) As Boolean
cmp = (i * log10(2) + j * log10(3) + k * log10(5)) > (gn(0) * log10(2) + gn(1) * log10(3) + gn(2) * log10(5))
End Function
Private Function count(N As Long, step As Integer) As Long
'Loop over y and z, compute x and
'count number of lattice points within tetrahedron.
'Step 1 is indirectly called by find_seed to calibrate the plane through A, B and C
'Step 2 fills the matrix cnt with the number of lattice points given the exponents of 3 and 5
'Step 3 the plane is lowered marginally so one or two candidates stick out
Dim M As Long, j As Integer, k As Integer
If step = 2 Then ReDim cnt(0 To Int(b) + 1, 0 To Int(c) + 1)
M = 0: j = 0: k = 0
Do While -c * j - b * k + b * c > 0
Do While -c * j - b * k + b * c > 0
Select Case step
Case 1: M = M + Int(x_given_y_z(j, k))
Case 2
cnt(j, k) = Int(x_given_y_z(j, k))
Case 3
If Int(x_given_y_z(j, k)) < cnt(j, k) Then
'This is a candidate, and ...
If cmp(cnt(j, k), j, k, hn) Then
'it is bigger dan what is already in hn
hn(0) = cnt(j, k)
hn(1) = j
hn(2) = k
End If
End If
End Select
k = k + 1
Loop
k = 0
j = j + 1
Loop
count = M
End Function
Private Sub list_upto(ByVal N As Integer)
Dim count As Integer
count = 1
Dim hn As Integer
hn = 1
Do While count < N
k = hn
Do While k Mod 2 = 0
k = k / 2
Loop
Do While k Mod 3 = 0
k = k / 3
Loop
Do While k Mod 5 = 0
k = k / 5
Loop
If k = 1 Then
Debug.Print hn; " ";
count = count + 1
End If
hn = hn + 1
Loop
Debug.Print
End Sub
Private Function find_seed(N As Long, step As Integer) As Long
Dim initial As Long, total As Long
initial = N
Do 'a simple iterative goal search, takes a handful iterations only
init initial
total = count(initial, step)
initial = initial + N - total
Loop Until total = N
find_seed = initial
End Function
Private Sub find_hn(N As Long)
Dim fs As Long, err As Long
'Step 1: find fs such that the number of lattice points is exactly N
fs = find_seed(N, 1)
'Step 2: fill the matrix cnt
init fs
err = count(fs, 2)
'Step 3: lower the plane by diminishing fs, the candidates for
'the Nth Hamming number will stick out and be recorded in hn
init fs - 1
err = count(fs - 1, 3)
Debug.Print "2^" & hn(0) - 1; " * 3^" & hn(1); " * 5^" & hn(2); "=";
If N < 1692 Then
'The task set a limit on the number size
Debug.Print pow(2, hn(0) - 1) * pow(3, hn(1)) * pow(5, hn(2))
Else
Debug.Print
If N <= 1000000 Then
'The big Hamming Number will end in a lot of zeroes. The common exponents of 2 and 5
'are split off to be printed separately.
If hn(0) - 1 < hn(2) Then
'Conversion to Decimal datatype with CDec allows to print numbers upto 10^28
Debug.Print CDec(pow(3, hn(1))) * CDec(pow(5, hn(2) - hn(0) + 1)) & String$(hn(0) - 1, "0")
Else
Debug.Print CDec(pow(2, hn(0) - 1 - hn(2))) * CDec(pow(3, hn(1))) & String$(hn(2), "0")
End If
End If
End If
End Sub
Public Sub main()
Dim start_time As Long, finis_time As Long
start_time = GetTickCount
Debug.Print "The first twenty Hamming numbers are:"
list_upto 20
Debug.Print "Hamming number 1691 is: ";
find_hn 1691
Debug.Print "Hamming number 1000000 is: ";
find_hn 1000000
finis_time = GetTickCount
Debug.Print "Execution time"; (finis_time - start_time); " milliseconds"
End Sub
|
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)
|
#Seed7
|
Seed7
|
$ include "seed7_05.s7i";
const integer: lower_limit is 0;
const integer: upper_limit is 100;
const proc: main is func
local
var integer: number is 0;
var integer: guess is 0;
begin
number := rand(lower_limit, upper_limit);
write("Guess the number between " <& lower_limit <& " and " <& upper_limit <& ": ");
while succeeds(readln(guess)) and number <> guess do
write("Your guess was too ");
if number < guess then
writeln("high.");
else
writeln("low.");
end if;
write("Try again: ");
end while;
if number = guess then
writeln("You guessed correctly!");
else
writeln("You gave up!");
end if;
end func;
|
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)
|
#Sidef
|
Sidef
|
var number = rand(1..10);
say "Guess the number between 1 and 10";
loop {
given(var n = Sys.scanln("> ").to_i) {
when (number) { say "You guessed it."; break }
case (n < number) { say "Too low" }
default { say "Too high" }
}
}
|
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
|
#Raku
|
Raku
|
sub happy (Int $n is copy --> Bool) {
loop {
state %seen;
$n = [+] $n.comb.map: { $_ ** 2 }
return True if $n == 1;
return False if %seen{$n}++;
}
}
say join ' ', grep(&happy, 1 .. *)[^8];
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#LC3_Assembly
|
LC3 Assembly
|
.orig x3000
LEA R0, hello ; R0 = &hello
TRAP x22 ; PUTS (print char array at addr in R0)
HALT
hello .stringz "Hello World!"
.end
|
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!
|
#Icon_and_Unicon
|
Icon and Unicon
|
procedure main()
x := 1
y := 2
x :=: y
write(x," ",y)
# swap that will reverse if surrounding expression fails
if x <-> y & x < y then write(x, " ", y)
end
|
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.
|
#K
|
K
|
|/ 6 1 7 4
7
|
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.
|
#Genyris
|
Genyris
|
def gcd (u v)
u = (abs u)
v = (abs v)
cond
(equal? v 0) u
else (gcd v (% u v))
|
http://rosettacode.org/wiki/Greatest_common_divisor
|
Greatest common divisor
|
Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related task
least common multiple.
See also
MathWorld entry: greatest common divisor.
Wikipedia entry: greatest common divisor.
|
#GFA_Basic
|
GFA Basic
|
'
' Greatest Common Divisor
'
a%=24
b%=112
PRINT "GCD of ";a%;" and ";b%;" is ";@gcd(a%,b%)
'
' Function computes gcd
'
FUNCTION gcd(a%,b%)
LOCAL t%
'
WHILE b%<>0
t%=a%
a%=b%
b%=t% MOD b%
WEND
'
RETURN ABS(a%)
ENDFUNC
|
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).
|
#J
|
J
|
hailseq=: -:`(1 3&p.)@.(2&|) ^:(1 ~: ]) ^:a:"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).
|
#VBScript
|
VBScript
|
For h = 1 To 20
WScript.StdOut.Write "H(" & h & ") = " & Hamming(h)
WScript.StdOut.WriteLine
Next
WScript.StdOut.Write "H(" & 1691 & ") = " & Hamming(1691)
WScript.StdOut.WriteLine
Function Hamming(l)
Dim h() : Redim h(l) : h(0) = 1
i = 0 : j = 0 : k = 0
x2 = 2 : x3 = 3 : x5 = 5
For n = 1 To l-1
m = x2
If m > x3 Then m = x3 End If
If m > x5 Then m = x5 End If
h(n) = m
If m = x2 Then i = i + 1 : x2 = 2 * h(i) End If
If m = x3 Then j = j + 1 : x3 = 3 * h(j) End If
If m = x5 Then k = k + 1 : x5 = 5 * h(k) End If
Next
Hamming = h(l-1)
End Function
|
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)
|
#Small_Basic
|
Small Basic
|
number=Math.GetRandomNumber(10)
TextWindow.WriteLine("I just thought of a number between 1 and 10. What is it?")
While guess<>number
guess=TextWindow.ReadNumber()
If guess>number Then
TextWindow.WriteLine("Lower number!")
EndIf
If guess<number Then
TextWindow.WriteLine("Higher number!")
EndIf
EndWhile
TextWindow.WriteLine("You win!")
|
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)
|
#Smalltalk
|
Smalltalk
|
'From Pharo7.0.3 of 12 April 2019 [Build information: Pharo-7.0.3+build.158.sha.0903ade8a6c96633f07e0a7f1baa9a5d48cfdf55 (64 Bit)] on 30 October 2019 at 4:24:17.115807 pm'!
Object subclass: #GuessingGame
instanceVariableNames: 'min max uiManager tries'
classVariableNames: ''
poolDictionaries: ''
category: 'GuessingGame'!
!GuessingGame methodsFor: 'initialization' stamp: 'EduardoPadoan 10/26/2019 23:51'!
initialize
uiManager := UIManager default.
tries := 0! !
!GuessingGame methodsFor: 'services' stamp: 'EduardoPadoan 10/26/2019 23:40'!
alert: aString
uiManager alert: aString! !
!GuessingGame methodsFor: 'accessing' stamp: 'EduardoPadoan 10/26/2019 23:36'!
max
^ max! !
!GuessingGame methodsFor: 'accessing' stamp: 'EduardoPadoan 10/26/2019 23:36'!
min
^ min! !
!GuessingGame methodsFor: 'accessing' stamp: 'EduardoPadoan 10/26/2019 23:36'!
min: anObject
min := anObject! !
!GuessingGame methodsFor: 'accessing' stamp: 'EduardoPadoan 10/26/2019 23:36'!
max: anObject
max := anObject! !
!GuessingGame methodsFor: 'playing-main' stamp: 'EduardoPadoan 10/27/2019 00:18'!
play
| toGuess |
toGuess := self selectNumber.
[ :break |
| choice |
[
choice := self getGuessOrExitWith: break.
choice
ifNil: [ self alert: 'Invalid Input' ]
ifNotNil: [
self incrementTries.
choice = toGuess
ifTrue: [ self congratulateForGuess: choice andExitWith: break ]
ifFalse: [ choice > toGuess ifTrue: [ self alert: 'Too high' ]
ifFalse: [ self alert: 'Too low' ] ]
]
] repeat.
] valueWithExit.! !
!GuessingGame methodsFor: 'as yet unclassified' stamp: 'EduardoPadoan 10/26/2019 23:39'!
makeRequest: aString
^ uiManager request: aString! !
!GuessingGame methodsFor: 'as yet unclassified' stamp: 'EduardoPadoan 10/26/2019 23:48'!
getGuessOrExitWith: anExitBlock
^ [(self makeRequest: 'Guess number a between , min,' and ', max, '.') asInteger]
on: MessageNotUnderstood "nil"
do: [
self sayGoodbye.
anExitBlock value ].! !
!GuessingGame methodsFor: 'as yet unclassified' stamp: 'EduardoPadoan 10/26/2019 23:51'!
incrementTries
tries := tries + 1! !
!GuessingGame methodsFor: 'as yet unclassified' stamp: 'EduardoPadoan 10/27/2019 00:05'!
sayGoodbye
self alert: 'Gave up? Sad.'.! !
!GuessingGame methodsFor: 'as yet unclassified' stamp: 'EduardoPadoan 10/27/2019 00:15'!
congratulateForGuess: anInteger andExitWith: anExitBlock
self alert: 'Correct!! The value was indeed ', anInteger asString, '. Took you only ', tries asString, ' tries.'.
^ anExitBlock value! !
!GuessingGame methodsFor: 'as yet unclassified' stamp: 'EduardoPadoan 10/26/2019 23:35'!
selectNumber
^ (min to: max) atRandom ! !
"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!
GuessingGame class
slots: { }!
!GuessingGame class methodsFor: 'creating' stamp: 'EduardoPadoan 10/27/2019 00:15'!
playFrom: aMinNumber to: aMaxNumber
self new
min: aMinNumber;
max: aMaxNumber;
play! !
|
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
|
#Relation
|
Relation
|
function happy(x)
set y = x
set lasty = 0
set found = " "
while y != 1 and not (found regex "\s".y."\s")
set found = found . y . " "
set m = 0
while y > 0
set digit = y mod 10
set m = m + digit * digit
set y = (y - digit) / 10
end while
set y = format(m,"%1d")
end while
set found = found . y . " "
if y = 1
set result = 1
else
set result = 0
end if
end function
set c = 0
set i = 1
while c < 8 and i < 100
if happy(i)
echo i
set c = c + 1
end if
set i = i + 1
end while
|
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
|
#LDPL
|
LDPL
|
procedure:
display "Hello World!" crlf
|
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!
|
#IDL
|
IDL
|
pro swap, a, b
c = temporary(a)
a = temporary(b)
b = temporary(c)
end
|
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.
|
#Klingphix
|
Klingphix
|
include ..\Utilitys.tlhy
( "1" "1234" "62" "234" "12" "34" "6" )
dup "Alphabetic order: " print lmax ?
:f tonum ;
@f map
"Numeric order: " print lmax ?
" " input
|
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.
|
#Klong
|
Klong
|
list::[ 1.0 2.3 1.1 5.0 3 2.8 2.01 3.14159 77 ]
|/list
|/ [ 1.0 2.3 1.1 5.0 3 2.8 2.01 3.14159 66 ]
|/ 1.0,2.3,1.1,5.0,3,2.8,2.01,3.14159,55
|
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.
|
#GML
|
GML
|
var n,m,r;
n = max(argument0,argument1);
m = min(argument0,argument1);
while (m != 0)
{
r = n mod m;
n = m;
m = r;
}
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).
|
#Java
|
Java
|
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class Hailstone {
public static List<Long> getHailstoneSequence(long n) {
if (n <= 0)
throw new IllegalArgumentException("Invalid starting sequence number");
List<Long> list = new ArrayList<Long>();
list.add(Long.valueOf(n));
while (n != 1) {
if ((n & 1) == 0)
n = n / 2;
else
n = 3 * n + 1;
list.add(Long.valueOf(n));
}
return list;
}
public static void main(String[] args) {
List<Long> sequence27 = getHailstoneSequence(27);
System.out.println("Sequence for 27 has " + sequence27.size() + " elements: " + sequence27);
long MAX = 100000;
// Simple way
{
long highestNumber = 1;
int highestCount = 1;
for (long i = 2; i < MAX; i++) {
int count = getHailstoneSequence(i).size();
if (count > highestCount) {
highestCount = count;
highestNumber = i;
}
}
System.out.println("Method 1, number " + highestNumber + " has the longest sequence, with a length of " + highestCount);
}
// More memory efficient way
{
long highestNumber = 1;
int highestCount = 1;
for (long i = 2; i < MAX; i++) {
int count = 1;
long n = i;
while (n != 1) {
if ((n & 1) == 0)
n = n / 2;
else
n = 3 * n + 1;
count++;
}
if (count > highestCount) {
highestCount = count;
highestNumber = i;
}
}
System.out.println("Method 2, number " + highestNumber + " has the longest sequence, with a length of " + highestCount);
}
// Efficient for analyzing all sequences
{
long highestNumber = 1;
long highestCount = 1;
Map<Long, Integer> sequenceMap = new HashMap<Long, Integer>();
sequenceMap.put(Long.valueOf(1), Integer.valueOf(1));
List<Long> currentList = new ArrayList<Long>();
for (long i = 2; i < MAX; i++) {
currentList.clear();
Long n = Long.valueOf(i);
Integer count = null;
while ((count = sequenceMap.get(n)) == null) {
currentList.add(n);
long nValue = n.longValue();
if ((nValue & 1) == 0)
n = Long.valueOf(nValue / 2);
else
n = Long.valueOf(3 * nValue + 1);
}
int curCount = count.intValue();
for (int j = currentList.size() - 1; j >= 0; j--)
sequenceMap.put(currentList.get(j), Integer.valueOf(++curCount));
if (curCount > highestCount) {
highestCount = curCount;
highestNumber = i;
}
}
System.out.println("Method 3, number " + highestNumber + " has the longest sequence, with a length of " + highestCount);
}
return;
}
}
|
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).
|
#Vlang
|
Vlang
|
import math.big
fn min(a big.Integer, b big.Integer) big.Integer {
if a < b {
return a
}
return b
}
fn hamming(n int) []big.Integer {
mut h := []big.Integer{len: n}
h[0] = big.one_int
two, three, five := big.two_int, big.integer_from_int(3), big.integer_from_int(5)
mut next2, mut next3, mut next5 := big.two_int, big.integer_from_int(3), big.integer_from_int(5)
mut i, mut j, mut k := 0, 0, 0
for m in 1..h.len {
h[m] = min(next2, min(next3, next5))
if h[m] == next2 {
i++
next2 = two * h[i]
}
if h[m] == next3 {
j++
next3 = three * h[j]
}
if h[m] == next5 {
k++
next5 = five * h[k]
}
}
return h
}
fn main() {
h := hamming(int(1e6))
println(h[..20])
println(h[1691-1])
println(h[h.len-1])
}
|
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)
|
#Sparkling
|
Sparkling
|
printf("Lower bound: ");
let lowerBound = toint(getline());
printf("Upper bound: ");
let upperBound = toint(getline());
assert(upperBound > lowerBound, "upper bound must be greater than lower bound");
seed(time());
let n = floor(random() * (upperBound - lowerBound) + lowerBound);
var guess;
print();
while true {
printf("Your guess: ");
guess = toint(getline());
if guess < n {
print("too low");
} else if guess > n {
print("too high");
} else {
print("You guessed it!");
break;
}
}
|
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
|
#REXX
|
REXX
|
/*REXX program computes and displays a specified amount of happy numbers. */
parse arg limit . /*obtain optional argument from the CL.*/
if limit=='' | limit=="," then limit=8 /*Not specified? Then use the default.*/
haps=0 /*count of the happy numbers (so far).*/
do n=1 while haps<limit; @.=0; q=n /*search the integers starting at unity*/
do until q==1 /*determine if Q is a happy number.*/
s=0 /*prepare to add squares of digits. */
do j=1 for length(q) /*sum the squares of the decimal digits*/
s=s + substr(q, j, 1) **2 /*add the square of a decimal digit.*/
end /*j*/
if @.s then iterate n /*if already summed, Q is unhappy. */
@.s=1; q=s /*mark the sum as found; try Q sum.*/
end /*until*/
say n /*display the number (N is happy). */
haps=haps+1 /*bump the count of happy numbers. */
end /*n*/
/*stick a fork in it, we're all done. */
|
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
|
#Lean
|
Lean
|
#eval "Hello world!"
|
http://rosettacode.org/wiki/Generic_swap
|
Generic swap
|
Task
Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types.
If your solution language is statically typed please describe the way your language provides genericity.
If variables are typed in the given language, it is permissible that the two variables be constrained to having a mutually compatible type, such that each is permitted to hold the value previously stored in the other without a type violation.
That is to say, solutions do not have to be capable of exchanging, say, a string and integer value, if the underlying storage locations are not attributed with types that permit such an exchange.
Generic swap is a task which brings together a few separate issues in programming language semantics.
Dynamically typed languages deal with values in a generic way quite readily, but do not necessarily make it easy to write a function to destructively swap two variables, because this requires indirection upon storage places or upon the syntax designating storage places.
Functional languages, whether static or dynamic, do not necessarily allow a destructive operation such as swapping two variables regardless of their generic capabilities.
Some static languages have difficulties with generic programming due to a lack of support for (Parametric Polymorphism).
Do your best!
|
#IS-BASIC
|
IS-BASIC
|
100 DEF SWAP(REF A,REF B)
110 LET T=A:LET A=B:LET B=T
120 END DEF
130 LET A=1:LET B=2
140 PRINT A,B
150 CALL SWAP(A,B)
160 PRINT 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.
|
#Kotlin
|
Kotlin
|
// version 1.0.5-2
fun main(args: Array<String>) {
print("Number of values to be input = ")
val n = readLine()!!.toInt()
val array = DoubleArray(n)
for (i in 0 until n) {
print("Value ${i + 1} = ")
array[i] = readLine()!!.toDouble()
}
println("\nThe greatest element is ${array.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.
|
#gnuplot
|
gnuplot
|
gcd (a, b) = b == 0 ? a : gcd (b, a % b)
|
http://rosettacode.org/wiki/Hailstone_sequence
|
Hailstone sequence
|
The Hailstone sequence of numbers can be generated from a starting positive integer, n by:
If n is 1 then the sequence ends.
If n is even then the next n of the sequence = n/2
If n is odd then the next n of the sequence = (3 * n) + 1
The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates.
This sequence was named by Lothar Collatz in 1937 (or possibly in 1939), and is also known as (the):
hailstone sequence, hailstone numbers
3x + 2 mapping, 3n + 1 problem
Collatz sequence
Hasse's algorithm
Kakutani's problem
Syracuse algorithm, Syracuse problem
Thwaites conjecture
Ulam's problem
The hailstone sequence is also known as hailstone numbers (because the values are usually subject to multiple descents and ascents like hailstones in a cloud).
Task
Create a routine to generate the hailstone sequence for a number.
Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1
Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.
(But don't show the actual sequence!)
See also
xkcd (humourous).
The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).
The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).
|
#JavaScript
|
JavaScript
|
function hailstone (n) {
var seq = [n];
while (n > 1) {
n = n % 2 ? 3 * n + 1 : n / 2;
seq.push(n);
}
return seq;
}
// task 2: verify the sequence for n = 27
var h = hailstone(27), hLen = h.length;
print("sequence 27 is (" + h.slice(0, 4).join(", ") + " ... "
+ h.slice(hLen - 4, hLen).join(", ") + "). length: " + hLen);
// task 3: find the longest sequence for n < 100000
for (var n, max = 0, i = 100000; --i;) {
var seq = hailstone(i), sLen = seq.length;
if (sLen > max) {
n = i;
max = sLen;
}
}
print("longest sequence: " + max + " numbers for starting point " + n);
|
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).
|
#Wren
|
Wren
|
import "/big" for BigInt, BigInts
var primes = [2, 3, 5].map { |p| BigInt.new(p) }.toList
var hamming = Fn.new { |size|
if (size < 1) Fiber.abort("size must be at least 1")
var ns = List.filled(size, null)
ns[0] = BigInt.one
var next = primes.toList
var indices = List.filled(3, 0)
for (m in 1...size) {
ns[m] = BigInts.min(next)
for (i in 0..2) {
if (ns[m] == next[i]) {
indices[i] = indices[i] + 1
next[i] = primes[i] * ns[indices[i]]
}
}
}
return ns
}
var h = hamming.call(1e6)
System.print("The first 20 Hamming numbers are:")
System.print(h[0..19])
System.print()
System.print("The 1,691st Hamming number is:")
System.print(h[1690])
System.print()
System.print("The 1,000,000th Hamming number is:")
System.print(h[999999])
|
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)
|
#Swift
|
Swift
|
import Cocoa
var found = false
let randomNum = Int(arc4random_uniform(100) + 1)
println("Guess a number between 1 and 100\n")
while (!found) {
var fh = NSFileHandle.fileHandleWithStandardInput()
println("Enter a number: ")
let data = fh.availableData
let str = NSString(data: data, encoding: NSUTF8StringEncoding)
if (str?.integerValue == randomNum) {
found = true
println("Well guessed!")
} else if (str?.integerValue < randomNum) {
println("Good try but the number is more than that!")
} else if (str?.integerValue > randomNum) {
println("Good try but the number is less than that!")
}
}
|
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
|
#Ring
|
Ring
|
n = 1
found = 0
While found < 8
If IsHappy(n)
found += 1
see string(found) + " : " + string(n) + nl
ok
n += 1
End
Func IsHappy n
cache = []
While n != 1
Add(cache,n)
t = 0
strn = string(n)
for e in strn
t += pow(number(e),2)
next
n = t
If find(cache,n) Return False ok
End
Return True
|
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
|
#LFE
|
LFE
|
(: io format '"Hello world!~n")
|
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!
|
#J
|
J
|
(<2 4) C. 2 3 5 7 11 13 17 19
2 3 11 7 5 13 17 19
(<0 3)&C.&.;:'Roses are red. Violets are blue.'
Violets are red. Roses are blue.
|
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.
|
#Lambdatalk
|
Lambdatalk
|
1) using the builtin primitive
{max 556 1 7344 4 7 52 22 55 88 122 55 99 1222 578}
-> 7344
2) buidling a function
{def my-max
{def max-h
{lambda {:l :greatest}
{if {A.empty? :l}
then :greatest
else {max-h {A.rest :l}
{if {> {A.first :l} :greatest}
then {A.first :l}
else :greatest}}}}}
{lambda {:l}
{if {A.empty? :l} then empty else {max-h :l {A.first :l}}}}}
-> my-max
{my-max {A.new 556 1 7344 4 7 52 22 55 88 122 55 99 1222 578}}
-> 7344
|
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.
|
#Go
|
Go
|
package main
import "fmt"
func gcd(a, b int) int {
var bgcd func(a, b, res int) int
bgcd = func(a, b, res int) int {
switch {
case a == b:
return res * a
case a % 2 == 0 && b % 2 == 0:
return bgcd(a/2, b/2, 2*res)
case a % 2 == 0:
return bgcd(a/2, b, res)
case b % 2 == 0:
return bgcd(a, b/2, res)
case a > b:
return bgcd(a-b, b, res)
default:
return bgcd(a, b-a, res)
}
}
return bgcd(a, b, 1)
}
func main() {
type pair struct {
a int
b int
}
var testdata []pair = []pair{
pair{33, 77},
pair{49865, 69811},
}
for _, v := range testdata {
fmt.Printf("gcd(%d, %d) = %d\n", v.a, v.b, gcd(v.a, v.b))
}
}
|
http://rosettacode.org/wiki/Hailstone_sequence
|
Hailstone sequence
|
The Hailstone sequence of numbers can be generated from a starting positive integer, n by:
If n is 1 then the sequence ends.
If n is even then the next n of the sequence = n/2
If n is odd then the next n of the sequence = (3 * n) + 1
The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates.
This sequence was named by Lothar Collatz in 1937 (or possibly in 1939), and is also known as (the):
hailstone sequence, hailstone numbers
3x + 2 mapping, 3n + 1 problem
Collatz sequence
Hasse's algorithm
Kakutani's problem
Syracuse algorithm, Syracuse problem
Thwaites conjecture
Ulam's problem
The hailstone sequence is also known as hailstone numbers (because the values are usually subject to multiple descents and ascents like hailstones in a cloud).
Task
Create a routine to generate the hailstone sequence for a number.
Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1
Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.
(But don't show the actual sequence!)
See also
xkcd (humourous).
The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).
The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).
|
#jq
|
jq
|
# Generate the hailstone sequence as a stream to save space (and time) when counting
def hailstone:
recurse( if . > 1 then
if . % 2 == 0 then ./2|floor else 3*. + 1 end
else empty
end );
def count(g): reduce g as $i (0; .+1);
# return [i, length] for the first maximal-length hailstone sequence where i is in [1 .. n]
def max_hailstone(n):
# state: [i, length]
reduce range(1; n+1) as $i
([0,0];
($i | count(hailstone)) as $l
| if $l > .[1] then [$i, $l] else . end);
|
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).
|
#Yabasic
|
Yabasic
|
dim h(1000000)
for i =1 to 20
print hamming(i)," ";
next i
print
print "Hamming List First(1691) = ",hamming(1691)
end
sub hamming(limit)
local x2,x3,x5,i,j,k,n
h(0) =1
x2 = 2: x3 = 3: x5 =5
i = 0: j = 0: k =0
for n =1 to limit
h(n) = min(x2, min(x3, x5))
if x2 = h(n) then i = i +1: x2 =2 *h(i):end if
if x3 = h(n) then j = j +1: x3 =3 *h(j):end if
if x5 = h(n) then k = k +1: x5 =5 *h(k):end if
next n
return h(limit -1)
end sub
|
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)
|
#Tcl
|
Tcl
|
set from 1
set to 10
set target [expr {int(rand()*($to-$from+1) + $from)}]
puts "I have thought of a number from $from to $to."
puts "Try to guess it!"
while 1 {
puts -nonewline "Enter your guess: "
flush stdout
gets stdin guess
if {![string is int -strict $guess] || $guess < $from || $guess > $to} {
puts "Your guess should be an integer from $from to $to (inclusive)."
} elseif {$guess > $target} {
puts "Your guess was too high. Try again!"
} elseif {$guess < $target} {
puts "Your guess was too low. Try again!"
} else {
puts "Well done! You guessed it."
break
}
}
|
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
|
#Ruby
|
Ruby
|
require 'set' # Set: Fast array lookup / Simple existence hash
@seen_numbers = Set.new
@happy_numbers = Set.new
def happy?(n)
return true if n == 1 # Base case
return @happy_numbers.include?(n) if @seen_numbers.include?(n) # Use performance cache, and stop unhappy cycles
@seen_numbers << n
digit_squared_sum = n.to_s.each_char.inject(0) { |sum, c| sum + c.to_i**2 } # In Rails: n.to_s.each_char.sum { c.to_i**2 }
if happy?(digit_squared_sum)
@happy_numbers << n
true # Return true
else
false # Return false
end
end
|
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
|
#Liberty_BASIC
|
Liberty BASIC
|
print "Hello world!"
|
http://rosettacode.org/wiki/Generic_swap
|
Generic swap
|
Task
Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types.
If your solution language is statically typed please describe the way your language provides genericity.
If variables are typed in the given language, it is permissible that the two variables be constrained to having a mutually compatible type, such that each is permitted to hold the value previously stored in the other without a type violation.
That is to say, solutions do not have to be capable of exchanging, say, a string and integer value, if the underlying storage locations are not attributed with types that permit such an exchange.
Generic swap is a task which brings together a few separate issues in programming language semantics.
Dynamically typed languages deal with values in a generic way quite readily, but do not necessarily make it easy to write a function to destructively swap two variables, because this requires indirection upon storage places or upon the syntax designating storage places.
Functional languages, whether static or dynamic, do not necessarily allow a destructive operation such as swapping two variables regardless of their generic capabilities.
Some static languages have difficulties with generic programming due to a lack of support for (Parametric Polymorphism).
Do your best!
|
#Java
|
Java
|
class Pair<T> {
T first;
T second;
}
public static <T> void swap(Pair<T> p) {
T temp = p.first;
p.first = p.second;
p.second = 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.
|
#Lasso
|
Lasso
|
define greatest(a::array) => {
return (#a->sort&)->last
}
local(x = array(556,1,7344,4,7,52,22,55,88,122,55,99,1222,578))
greatest(#x)
|
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.
|
#Golfscript
|
Golfscript
|
;'2706 410'
~{.@\%.}do;
|
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).
|
#Julia
|
Julia
|
function hailstonelength(n::Integer)
len = 1
while n > 1
n = ifelse(iseven(n), n ÷ 2, 3n + 1)
len += 1
end
return len
end
@show hailstonelength(27); nothing
@show findmax([hailstonelength(i) for i in 1:100_000]); nothing
|
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).
|
#zkl
|
zkl
|
var BN=Import("zklBigNum"); // only needed for large N
fcn hamming(N){
h:=List.createLong(N+1); (0).pump(N+1,h.write,Void); // fill list with stuff
h[0]=1;
#if 1 // regular (64 bit) ints
x2:=2; x3:=3; x5:=5; i:=j:=k:=0;
#else // big ints
x2:=BN(2); x3:=BN(3); x5:=BN(5); i:=j:=k:=0;
#endif
foreach n in ([1..N]){
z:=(x2<x3) and x2 or x3; z=(z<x5) and z or x5; h[n]=z;
if (h[n] == x2) { x2 = h[i+=1]*2 }
if (h[n] == x3) { x3 = h[j+=1]*3 }
if (h[n] == x5) { x5 = h[k+=1]*5 }
}
return(h[N-1])
}
[1..20].apply(hamming).println();
hamming(1691).println();
|
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)
|
#TUSCRIPT
|
TUSCRIPT
|
$$ MODE TUSCRIPT
PRINT "Find the luckynumber (7 tries)!"
SET luckynumber=RANDOM NUMBERS (1,100,1)
LOOP round=1,7
SET message=CONCAT ("[",round,"] Please insert a number")
ASK $message: n=""
IF (n!='digits') THEN
PRINT "wrong insert: ",n," Please insert a digit"
ELSEIF (n>100.or.n<1) THEN
PRINT "wrong insert: ",n," Please insert a number between 1-100"
ELSEIF (n==#luckynumber) THEN
PRINT "BINGO"
EXIT
ELSEIF (n.gt.#luckynumber) THEN
PRINT "too big"
ELSEIF (n.lt.#luckynumber) THEN
PRINT "too small"
ENDIF
IF (round==7) PRINT/ERROR "You've lost: luckynumber was: ",luckynumber
ENDLOOP
|
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)
|
#UNIX_Shell
|
UNIX Shell
|
function guess {
[[ -n $BASH_VERSION ]] && shopt -s extglob
[[ -n $ZSH_VERSION ]] && set -o KSH_GLOB
local -i max=${1:-100}
local -i number=RANDOM%max+1
local -i guesses=0
local guess
while true; do
echo -n "Guess my number! (range 1 - $max): "
read guess
if [[ "$guess" != +([0-9]) ]] || (( guess < 1 || guess > max )); then
echo "Guess must be a number between 1 and $max."
continue
fi
let guesses+=1
if (( guess < number )); then
echo "Too low!"
elif (( guess == number )); then
echo "You got it in $guesses guesses!"
break
else
echo "Too high!"
fi
done
}
|
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
|
#Run_BASIC
|
Run BASIC
|
for i = 1 to 100
if happy(i) = 1 then
cnt = cnt + 1
PRINT cnt;". ";i;" is a happy number "
if cnt = 8 then end
end if
next i
FUNCTION happy(num)
while count < 50 and happy <> 1
num$ = str$(num)
count = count + 1
happy = 0
for i = 1 to len(num$)
happy = happy + val(mid$(num$,i,1)) ^ 2
next i
num = happy
wend
end function
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#LIL
|
LIL
|
#
# Hello world in lil
#
print "Hello, world!"
|
http://rosettacode.org/wiki/Generic_swap
|
Generic swap
|
Task
Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types.
If your solution language is statically typed please describe the way your language provides genericity.
If variables are typed in the given language, it is permissible that the two variables be constrained to having a mutually compatible type, such that each is permitted to hold the value previously stored in the other without a type violation.
That is to say, solutions do not have to be capable of exchanging, say, a string and integer value, if the underlying storage locations are not attributed with types that permit such an exchange.
Generic swap is a task which brings together a few separate issues in programming language semantics.
Dynamically typed languages deal with values in a generic way quite readily, but do not necessarily make it easy to write a function to destructively swap two variables, because this requires indirection upon storage places or upon the syntax designating storage places.
Functional languages, whether static or dynamic, do not necessarily allow a destructive operation such as swapping two variables regardless of their generic capabilities.
Some static languages have difficulties with generic programming due to a lack of support for (Parametric Polymorphism).
Do your best!
|
#JavaScript
|
JavaScript
|
function swap(arr) {
var tmp = arr[0];
arr[0] = arr[1];
arr[1] = 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.
|
#LFE
|
LFE
|
>(: lists max '[9 4 3 8 5])
9
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.