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).
|
#QBasic
|
QBasic
|
FUNCTION min (a, b)
IF a < b THEN min = a ELSE min = b
END FUNCTION
FUNCTION Hamming (limit)
DIM h(limit)
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
Hamming = h(limit - 1)
END FUNCTION
PRINT "The first 20 Hamming numbers are :"
FOR i = 1 TO 20
PRINT Hamming(i); " ";
NEXT i
PRINT
PRINT "H( 1691) = "; Hamming(1691)
|
http://rosettacode.org/wiki/Guess_the_number
|
Guess the number
|
Task
Write a program where the program chooses a number between 1 and 10.
A player is then prompted to enter a guess. If the player guesses wrong, then the prompt appears again until the guess is correct.
When the player has made a successful guess the computer will issue a "Well guessed!" message, and the program exits.
A conditional loop may be used to repeat the guessing until the user is correct.
Related tasks
Bulls and cows
Bulls and cows/Player
Guess the number/With Feedback
Mastermind
|
#SNUSP
|
SNUSP
|
/++.#
\>.--.++<..+ +\
/>+++++++.>-.+/
/ \ />++++++>++\
< + ?
< > \ -<<++++++/
$++++\ - + !
/++++/ > \++++++++++\
\+ %!/!\?/>>>,>>>>>>+++\/ !/?\<?\>>/
/++++++++++++++++/ > - \\
\+++++++++\ / / - <
/+++++++++/ \ /
\+++++++++++\ /++++++++++>>/
/<<<<<</?\!/ !
< - /-<<+++++++\
< > ?
< > \>+++++++>+/
< > >
< > .
< > \-----.>++\
- > /.+++.+++/
\ / \!/?\<!/?\ \
\ / \-/ \-/
\ <</?\!>/?\!</?\!<<</
\-/ > \-/
+ -
< >
< +
\ /
|
http://rosettacode.org/wiki/Guess_the_number
|
Guess the number
|
Task
Write a program where the program chooses a number between 1 and 10.
A player is then prompted to enter a guess. If the player guesses wrong, then the prompt appears again until the guess is correct.
When the player has made a successful guess the computer will issue a "Well guessed!" message, and the program exits.
A conditional loop may be used to repeat the guessing until the user is correct.
Related tasks
Bulls and cows
Bulls and cows/Player
Guess the number/With Feedback
Mastermind
|
#Swift
|
Swift
|
import Cocoa
var found = false
let randomNum = Int(arc4random_uniform(10) + 1)
println("Guess a number between 1 and 10\n")
while (!found) {
var fh = NSFileHandle.fileHandleWithStandardInput()
println("Enter a number: ")
let data = fh.availableData
var str = NSString(data: data, encoding: NSUTF8StringEncoding)
if (str?.integerValue == randomNum) {
found = true
println("Well guessed!")
}
}
|
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)
|
#NewLISP
|
NewLISP
|
; guess-number-feedback.lsp
; oofoe 2012-01-19
; http://rosettacode.org/wiki/Guess_the_number/With_feedback
(seed (time-of-day)) ; Initialize random number generator from clock.
(setq low -5
high 62
number (+ low (rand (- high low)))
found nil
)
(print "I'm thinking of a number between " low " and " high ".")
(while (not found)
(print " What's your guess? ")
(setq guess (int (read-line) 'bad))
(print (cond ((= 'bad guess) "That's not a number! Try again!")
((or (< guess low) (> guess high))
(string "My number is between " low
" and " high ". Try again!"))
((< number guess) "Try a little lower...")
((> number guess) "Maybe a bit higher...")
((= number guess) (setq found true) "Exactly right!")))
)
(println "\nWell guessed! Congratulations!")
(exit)
|
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
|
#OCaml
|
OCaml
|
open Num
let step =
let rec aux s n =
if n =/ Int 0 then s else
let q = quo_num n (Int 10)
and r = mod_num n (Int 10)
in aux (s +/ (r */ r)) q
in aux (Int 0) ;;
let happy n =
let rec aux x y =
if x =/ y then x else aux (step x) (step (step y))
in (aux n (step n)) =/ Int 1 ;;
let first n =
let rec aux v x n =
if n = 0 then v else
if happy x
then aux (x::v) (x +/ Int 1) (n - 1)
else aux v (x +/ Int 1) n
in aux [ ] (Int 1) n ;;
List.iter print_endline (
List.rev_map string_of_num (first 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
|
#jq
|
jq
|
"Hello world!"
|
http://rosettacode.org/wiki/Hello_world/Graphical
|
Hello world/Graphical
|
Task
Display the string Goodbye, World! on a GUI object (alert box, plain window, text area, etc.).
Related task
Hello world/Text
|
#Tosh
|
Tosh
|
when flag clicked
say "Goodbye, World!"
stop this script
|
http://rosettacode.org/wiki/Hello_world/Graphical
|
Hello world/Graphical
|
Task
Display the string Goodbye, World! on a GUI object (alert box, plain window, text area, etc.).
Related task
Hello world/Text
|
#TXR
|
TXR
|
(with-dyn-lib "user32.dll"
(deffi messagebox "MessageBoxW" int (cptr wstr wstr uint)))
(messagebox cptr-null "Hello" "World" 0) ;; 0 is MB_OK
|
http://rosettacode.org/wiki/Gray_code
|
Gray code
|
Gray code
Karnaugh maps
Create functions to encode a number to and decode a number from Gray code.
Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary).
There are many possible Gray codes. The following encodes what is called "binary reflected Gray code."
Encoding (MSB is bit 0, b is binary, g is Gray code):
if b[i-1] = 1
g[i] = not b[i]
else
g[i] = b[i]
Or:
g = b xor (b logically right shifted 1 time)
Decoding (MSB is bit 0, b is binary, g is Gray code):
b[0] = g[0]
for other bits:
b[i] = g[i] xor b[i-1]
Reference
Converting Between Gray and Binary Codes. It includes step-by-step animations.
|
#VHDL
|
VHDL
|
LIBRARY ieee;
USE ieee.std_logic_1164.all;
entity b2g is
port( bin : in std_logic_vector (4 downto 0);
gray : out std_logic_vector (4 downto 0)
);
end b2g ;
architecture rtl of b2g is
constant N : integer := bin'high;
begin
gray <= bin(n) & ( bin(N-1 downto 0) xor bin(N downto 1));
end architecture rtl;
|
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!
|
#Elixir
|
Elixir
|
x = 4
y = 5
{y,x} = {x,y}
y # => 4
x # => 5
[x,y] = [y,x]
x # => 4
y # => 5
|
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.
|
#Erlang
|
Erlang
|
>lists:max([9,4,3,8,5]).
9
|
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.
|
#EasyLang
|
EasyLang
|
func gcd a b . res .
while b <> 0
h = b
b = a mod b
a = h
.
res = a
.
call gcd 120 35 r
print r
|
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).
|
#Excel
|
Excel
|
In cell A1, place the starting number.
In cell A2 enter this formula =IF(MOD(A1,2)=0,A1/2,A1*3+1)
Drag and copy the formula down until 4, 2, 1
|
http://rosettacode.org/wiki/Hamming_numbers
|
Hamming numbers
|
Hamming numbers are numbers of the form
H = 2i × 3j × 5k
where
i, j, k ≥ 0
Hamming numbers are also known as ugly numbers and also 5-smooth numbers (numbers whose prime divisors are less or equal to 5).
Task
Generate the sequence of Hamming numbers, in increasing order. In particular:
Show the first twenty Hamming numbers.
Show the 1691st Hamming number (the last one below 231).
Show the one millionth Hamming number (if the language – or a convenient library – supports arbitrary-precision integers).
Related tasks
Humble numbers
N-smooth numbers
References
Wikipedia entry: Hamming numbers (this link is re-directed to Regular number).
Wikipedia entry: Smooth number
OEIS entry: A051037 5-smooth or Hamming numbers
Hamming problem from Dr. Dobb's CodeTalk (dead link as of Sep 2011; parts of the thread here and here).
|
#Qi
|
Qi
|
(define smerge
[X|Xs] [Y|Ys] -> [X | (freeze (smerge (thaw Xs) [Y|Ys]))] where (< X Y)
[X|Xs] [Y|Ys] -> [Y | (freeze (smerge [X|Xs] (thaw Ys)))] where (> X Y)
[X|Xs] [_|Ys] -> [X | (freeze (smerge (thaw Xs) (thaw Ys)))])
(define smerge3
Xs Ys Zs -> (smerge Xs (smerge Ys Zs)))
(define smap
F [S|Ss] -> [(F S)|(freeze (smap F (thaw Ss)))])
(set hamming [1 | (freeze (smerge3 (smap (* 2) (value hamming))
(smap (* 3) (value hamming))
(smap (* 5) (value hamming))))])
(define stake
_ 0 -> []
[S|Ss] N -> [S|(stake (thaw Ss) (1- N))])
(stake (value hamming) 20)
|
http://rosettacode.org/wiki/Guess_the_number
|
Guess the number
|
Task
Write a program where the program chooses a number between 1 and 10.
A player is then prompted to enter a guess. If the player guesses wrong, then the prompt appears again until the guess is correct.
When the player has made a successful guess the computer will issue a "Well guessed!" message, and the program exits.
A conditional loop may be used to repeat the guessing until the user is correct.
Related tasks
Bulls and cows
Bulls and cows/Player
Guess the number/With Feedback
Mastermind
|
#Tcl
|
Tcl
|
set target [expr {int(rand()*10 + 1)}]
puts "I have thought of a number."
puts "Try to guess it!"
while 1 {
puts -nonewline "Enter your guess: "
flush stdout
gets stdin guess
if {$guess == $target} {
break
}
puts "Your guess was wrong. Try again!"
}
puts "Well done! You guessed it."
|
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)
|
#Nim
|
Nim
|
import random, strutils
randomize()
let iRange = 1..100
echo "Guess my target number that is between ", iRange.a, " and ", iRange.b, " (inclusive)."
let target = rand(iRange)
var answer, i = 0
while answer != target:
inc i
stdout.write "Your guess ", i, ": "
let txt = stdin.readLine()
try: answer = parseInt(txt)
except ValueError:
echo " I don't understand your input of '", txt, "'"
continue
if answer notin iRange: echo " Out of range!"
elif answer < target: echo " Too low."
elif answer > target: echo " Too high."
else: echo " Ye-Haw!!"
echo "Thanks for playing."
|
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
|
#Oforth
|
Oforth
|
: isHappy(n)
| cycle |
ListBuffer new ->cycle
while(n 1 <>) [
cycle include(n) ifTrue: [ false return ]
cycle add(n)
0 n asString apply(#[ asDigit sq + ]) ->n
]
true ;
: happyNum(N)
| numbers |
ListBuffer new ->numbers
1 while(numbers size N <>) [ dup isHappy ifTrue: [ dup numbers add ] 1+ ]
numbers println ;
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#JSE
|
JSE
|
Print "Hello world!"
|
http://rosettacode.org/wiki/Hello_world/Graphical
|
Hello world/Graphical
|
Task
Display the string Goodbye, World! on a GUI object (alert box, plain window, text area, etc.).
Related task
Hello world/Text
|
#UNIX_Shell
|
UNIX Shell
|
whiptail --title 'Farewell' --msgbox 'Goodbye, World!' 7 20
|
http://rosettacode.org/wiki/Gray_code
|
Gray code
|
Gray code
Karnaugh maps
Create functions to encode a number to and decode a number from Gray code.
Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary).
There are many possible Gray codes. The following encodes what is called "binary reflected Gray code."
Encoding (MSB is bit 0, b is binary, g is Gray code):
if b[i-1] = 1
g[i] = not b[i]
else
g[i] = b[i]
Or:
g = b xor (b logically right shifted 1 time)
Decoding (MSB is bit 0, b is binary, g is Gray code):
b[0] = g[0]
for other bits:
b[i] = g[i] xor b[i-1]
Reference
Converting Between Gray and Binary Codes. It includes step-by-step animations.
|
#Vlang
|
Vlang
|
fn enc(b int) int {
return b ^ b>>1
}
fn dec(gg int) int {
mut b := 0
mut g := gg
for ; g != 0; g >>= 1 {
b ^= g
}
return b
}
fn main() {
println("decimal binary gray decoded")
for b := 0; b < 32; b++ {
g := enc(b)
d := dec(g)
println(" ${b:2} ${b:05b} ${g:05b} ${d:05b} ${d:2}")
}
}
|
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!
|
#Emacs_Lisp
|
Emacs Lisp
|
(defun swap (a-sym b-sym)
"Swap values of the variables given by A-SYM and B-SYM."
(let ((a-val (symbol-value a-sym)))
(set a-sym (symbol-value b-sym))
(set b-sym a-val)))
(swap 'a 'b)
|
http://rosettacode.org/wiki/Greatest_element_of_a_list
|
Greatest element of a list
|
Task
Create a function that returns the maximum value in a provided set of values,
where the number of values may not be known until run-time.
|
#ERRE
|
ERRE
|
PROGRAM MAXLIST
!
! for rosettacode.org
!
! VAR L$,EL$,CH$,I%,MAX
BEGIN
PRINT(CHR$(12);) ! CLS
INPUT("Lista",L$)
L$=L$+CHR$(32)
MAX=-1.7E+38
FOR I%=1 TO LEN(L$) DO
CH$=MID$(L$,I%,1)
IF CH$<>CHR$(32) THEN ! blank is separator
EL$=EL$+CH$
ELSE
IF VAL(EL$)>MAX THEN MAX=VAL(EL$) END IF
EL$=""
END IF
END FOR
PRINT("Max list element is";MAX)
END PROGRAM
|
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.
|
#Euler_Math_Toolbox
|
Euler Math Toolbox
|
>v=random(1,100);
>max(v)
0.997492478596
|
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.
|
#EDSAC_order_code
|
EDSAC order code
|
[Greatest common divisor for Rosetta Code.
Program for EDSAC, Initial Orders 2.]
[Library subroutine R2. Reads positive integers during input of orders,
and is then overwritten (so doesn't take up any memory).
Negative numbers can be input by adding 2^35.
Each integer is followed by 'F', except the last is followed by '#TZ'.]
T 45 K [store address in location 45
values are then accessed by code letter H]
P 220 F [<------ address here]
GKT20FVDL8FA40DUDTFI40FA40FS39FG@S2FG23FA5@T5@E4@E13Z
T #H [Tell R2 the storage location defined above]
[Integers to be read by R2. First item is count, then pairs for GCD algo.]
4F 1066F 2019F 1815F 1914F 103785682F 167928761F 109876463F 177777648#TZ
[----------------------------------------------------------------------
Library subroutine P7.
Prints long strictly positive integer at 0D.
10 characters, right justified, padded left with spaces.
Closed, even; 35 storage locations; working position 4D.]
T 56 K
GKA3FT26@H28#@NDYFLDT4DS27@TFH8@S8@T1FV4DAFG31@SFLDUFOFFFSFL4F
T4DA1FA27@G11@XFT28#ZPFT27ZP1024FP610D@524D!FO30@SFL8FE22@
[---------------------------------------------------------------
Subroutine to return GCD of two non-negative 35-bit integers.
Input: Integers at 4D, 6D.
Output: GCD at 4D; changes 6D.
41 locations; working location 0D.]
T 100 K
G K
A 3 F [plant link]
T 39 @
S 4 D [test for 4D = 0]
E 37 @ [if so, quick exit, GCD = 6D]
T 40 @ [clear acc]
[5] A 4 D [load divisor]
[6] T D [initialize shifted divisor]
A 6 D [load dividend]
R D [shift 1 right]
S D [shifted divisor > dividend/2 yet?]
G 15 @ [yes, start subtraction]
T 40 @ [no, clear acc]
A D [shift divisor 1 more]
L D
E 6 @ [loop back (always, since acc = 0)]
[15] T 40 @ [clear acc]
[16] A 6 D [load remainder (initially = dividend)]
S D [trial subtraction]
G 20 @ [skip if can't subtract]
T 6 D [update remainder]
[20] T 40 @ [clear acc]
A 4 D [load original divisor]
S D [is shifted divisor back to original?]
E 29 @ [yes, jump out with acc = 0]
T 40 @ [no, clear acc]
A D [shift divisor 1 right]
R D
T D
E 16 @ [loop back (always, since acc = 0)]
[Here when finished dividing 6D by 4D.
Remainder is at 6D; acc = 0.]
[29] S 6 D [test for 6D = 0]
E 39 @ [if so, exit with GCD in 4D]
T D [else swap 4D and 6D]
A 4 D
T 6 D
S D
T 4 D
E 5 @ [loop back]
[37] A 6 D [here if 4D = 0 at start; GCD is 6D]
T 4 D [return in 4D as GCD]
[39] E F
[40] P F [junk word, to clear accumulator]
[----------------------------------------------------------------------
Main routine]
T 150 K
G K
[Variable]
[0] P F
[Constants]
[1] P D [single-word 1]
[2] A 2#H [order to load first number of first pair]
[3] P 2 F [to inc addresses by 2]
[4] # F [figure shift]
[5] K 2048 F [letter shift]
[6] G F [letters to print 'GCD']
[7] C F
[8] D F
[9] V F [equals sign (in figures mode)]
[10] ! F [space]
[11] @ F [carriage return]
[12] & F [line feed]
[13] K 4096 F [null char]
[Enter here with acc = 0]
[14] O 4 @ [set teleprinter to figures]
S H [negative of number of pairs]
T @ [initialize counter]
A 2 @ [initial load order]
[18] U 23 @ [plant order to load 1st integer]
U 32 @
A 3 @ [inc address by 2]
U 28 @ [plant order to load 2nd integer]
T 34 @
[23] A #H [load 1st integer (order set up at runtime)]
T D [to 0D for printing]
A 25 @ [for return from print subroutine]
G 56 F [print 1st number]
O 10 @ [followed by space]
[28] A #H [load 2nd integer (order set up at runtime)]
T D [to 0D for printing]
A 30 @ [for return from print subroutine]
G 56 F [print 2nd number]
[32] A #H [load 1st integer (order set up at runtime)]
T 4 D [to 4D for GCD subroutine]
[34] A #H [load 2nd integer (order set up at runtime)]
T 6 D [to 6D for GCD subroutine]
[36] A 36 @ [for return from subroutine]
G 100 F [call subroutine for GCD]
[Cosmetic printing, add ' GCD = ']
O 10 @
O 10 @
O 5 @
O 6 @
O 7 @
O 8 @
O 4 @
O 10 @
O 9 @
O 10 @
A 4 D [load GCD]
T D [to 0D for printing]
A 50 @ [for return from print subroutine]
G 56 F [print GCD]
O 11 @ [followed by new line]
O 12 @
[On to next pair]
A @ [load negative count of c.f.s]
A 1 @ [add 1]
E 62 @ [exit if count = 0]
T @ [store back]
A 23 @ [order to load first of pair]
A 3 @ [inc address by 4 for next c.f.]
A 3 @
G 18 @ [loop back (always, since 'A' < 0)]
[62] O 13 @ [null char to flush teleprinter buffer]
Z F [stop]
E 14 Z [define entry point]
P F [acc = 0 on entry]
|
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).
|
#Ezhil
|
Ezhil
|
நிரல்பாகம் hailstone ( எண் )
பதிப்பி "=> ",எண் #hailstone seq
@( எண் == 1 ) ஆனால்
பின்கொடு எண்
முடி
@( (எண்%2) == 1 ) ஆனால்
hailstone( 3*எண் + 1)
இல்லை
hailstone( எண்/2 )
முடி
முடி
எண்கள் = [5,17,19,23,37]
@(எண்கள் இல் இவ்வெண்) ஒவ்வொன்றாக
பதிப்பி "****** calculating hailstone seq for ",இவ்வெண்," *********"
hailstone( இவ்வெண் )
பதிப்பி "**********************************************"
முடி
|
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).
|
#Quackery
|
Quackery
|
' [ 2 3 5 ] smoothwith [ size 1000000 = ]
dup 20 split drop echo cr
dup 1690 peek echo cr
-1 peek echo
|
http://rosettacode.org/wiki/Guess_the_number
|
Guess the number
|
Task
Write a program where the program chooses a number between 1 and 10.
A player is then prompted to enter a guess. If the player guesses wrong, then the prompt appears again until the guess is correct.
When the player has made a successful guess the computer will issue a "Well guessed!" message, and the program exits.
A conditional loop may be used to repeat the guessing until the user is correct.
Related tasks
Bulls and cows
Bulls and cows/Player
Guess the number/With Feedback
Mastermind
|
#TUSCRIPT
|
TUSCRIPT
|
$$ MODE TUSCRIPT
PRINT "Find the luckynumber (7 tries)!"
luckynumber=RANDOM_NUMBERS (1,10,1)
COMPILE
LOOP round=1,7
message=CONCAT ("[",round,"] Please insert a number")
ASK $message: n=""
IF (n!='digits') THEN
PRINT "wrong insert: ",n," Please insert a digit"
ELSEIF (n>10.or.n<1) THEN
PRINT "wrong insert: ",n," Please insert a number between 1-10"
ELSEIF (n==#luckynumber) THEN
PRINT "BINGO"
EXIT
ENDIF
IF (round==7) PRINT/ERROR "You've lost: luckynumber was: ",luckynumber
ENDLOOP
ENDCOMPILE
|
http://rosettacode.org/wiki/Guess_the_number
|
Guess the number
|
Task
Write a program where the program chooses a number between 1 and 10.
A player is then prompted to enter a guess. If the player guesses wrong, then the prompt appears again until the guess is correct.
When the player has made a successful guess the computer will issue a "Well guessed!" message, and the program exits.
A conditional loop may be used to repeat the guessing until the user is correct.
Related tasks
Bulls and cows
Bulls and cows/Player
Guess the number/With Feedback
Mastermind
|
#UNIX_Shell
|
UNIX Shell
|
#!/bin/sh
# Guess the number
# This simplified program does not check the input is valid
# Use awk(1) to get a random number. If awk(1) not found, exit now.
number=`awk 'BEGIN{print int(rand()*10+1)}'` || exit
echo 'I have thought of a number. Try to guess it!'
echo 'Enter an integer from 1 to 10.'
until read guess; [ "$guess" -eq "$number" ]
do
echo 'Sorry, the guess was wrong! Try again!'
done
echo 'Well done! You guessed it.'
|
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)
|
#NS-HUBASIC
|
NS-HUBASIC
|
10 NUMBER=RND(10)+1
20 INPUT "I'M THINKING OF A NUMBER BETWEEN 1 AND 10. WHAT IS IT? ",GUESS
30 IF GUESS>NUMBER THEN PRINT "MY NUMBER IS LOWER THAN THAT.": GOTO 20
40 IF GUESS<NUMBER THEN PRINT "MY NUMBER IS HIGHER THAN THAT.": GOTO 20
50 PRINT "THAT'S THE CORRECT NUMBER."
|
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)
|
#Objeck
|
Objeck
|
use IO;
bundle Default {
class GuessNumber {
function : Main(args : String[]) ~ Nil {
Guess();
}
function : native : Guess() ~ Nil {
done := false;
"Guess the number which is between 1 and 10 or 'n' to quite: "->PrintLine();
rand_num := (Float->Random() * 10.0)->As(Int) + 1;
while(done = false) {
guess := Console->ReadString();
number := guess->ToInt();
if(number <> 0) {
if(number <> rand_num) {
Console->Print("Your guess was too ")
->Print(number < rand_num ? "low" : "high")
->Print(".\nGuess again: ");
}
else {
"Hurray! You guessed correctly!"->PrintLine();
done := true;
};
}
else {
if(guess->StartsWith("q") | guess->StartsWith("Q")) {
done := true;
};
};
};
}
}
}
|
http://rosettacode.org/wiki/Happy_numbers
|
Happy numbers
|
From Wikipedia, the free encyclopedia:
A happy number is defined by the following process:
Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.
Those numbers for which this process end in 1 are happy numbers,
while those numbers that do not end in 1 are unhappy numbers.
Task
Find and print the first 8 happy numbers.
Display an example of your output here on this page.
See also
The OEIS entry: The happy numbers: A007770
The OEIS entry: The unhappy numbers; A031177
|
#ooRexx
|
ooRexx
|
count = 0
say "First 8 happy numbers are:"
loop i = 1 while count < 8
if happyNumber(i) then do
count += 1
say i
end
end
::routine happyNumber
use strict arg number
-- use to trace previous cycle results
previous = .set~new
loop forever
-- stop when we hit the target
if number = 1 then return .true
-- stop as soon as we start cycling
if previous[number] \== .nil then return .false
previous~put(number)
next = 0
-- loop over all of the digits
loop digit over number~makearray('')
next += digit * digit
end
-- and repeat the cycle
number = next
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
|
#Jsish
|
Jsish
|
puts("Hello world!")
|
http://rosettacode.org/wiki/Hello_world/Graphical
|
Hello world/Graphical
|
Task
Display the string Goodbye, World! on a GUI object (alert box, plain window, text area, etc.).
Related task
Hello world/Text
|
#Ultimate.2B.2B
|
Ultimate++
|
#include <CtrlLib/CtrlLib.h>
// submitted by Aykayayciti (Earl Lamont Montgomery)
using namespace Upp;
class GoodbyeWorld : public TopWindow {
MenuBar menu;
StatusBar status;
void FileMenu(Bar& bar);
void MainMenu(Bar& bar);
void About();
public:
typedef GoodbyeWorld CLASSNAME;
GoodbyeWorld();
};
void GoodbyeWorld::About()
{
PromptOK("{{1@5 [@9= This is the]::@2 [A5@0 Ultimate`+`+ Goodbye World sample}}");
}
void GoodbyeWorld::FileMenu(Bar& bar)
{
bar.Add("About..", THISBACK(About));
bar.Separator();
bar.Add("Exit", THISBACK(Close));
}
void GoodbyeWorld::MainMenu(Bar& bar)
{
menu.Add("File", THISBACK(FileMenu));
}
GoodbyeWorld::GoodbyeWorld()
{
AddFrame(menu);
AddFrame(status);
menu.Set(THISBACK(MainMenu));
status = "So long from the Ultimate++ !";
}
GUI_APP_MAIN
{
SetLanguage(LNG_ENGLISH);
GoodbyeWorld().Run();
}
|
http://rosettacode.org/wiki/Gray_code
|
Gray code
|
Gray code
Karnaugh maps
Create functions to encode a number to and decode a number from Gray code.
Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary).
There are many possible Gray codes. The following encodes what is called "binary reflected Gray code."
Encoding (MSB is bit 0, b is binary, g is Gray code):
if b[i-1] = 1
g[i] = not b[i]
else
g[i] = b[i]
Or:
g = b xor (b logically right shifted 1 time)
Decoding (MSB is bit 0, b is binary, g is Gray code):
b[0] = g[0]
for other bits:
b[i] = g[i] xor b[i-1]
Reference
Converting Between Gray and Binary Codes. It includes step-by-step animations.
|
#Wren
|
Wren
|
import "/fmt" for Fmt
var toGray = Fn.new { |n| n ^ (n>>1) }
var fromGray = Fn.new { |g|
var b = 0
while (g != 0) {
b = b ^ g
g = g >> 1
}
return b
}
System.print("decimal binary gray decoded")
for (b in 0..31) {
System.write(" %(Fmt.d(2, b)) %(Fmt.bz(5, b))")
var g = toGray.call(b)
System.write(" %(Fmt.bz(5, g))")
System.print(" %(Fmt.bz(5, fromGray.call(g)))")
}
|
http://rosettacode.org/wiki/Gray_code
|
Gray code
|
Gray code
Karnaugh maps
Create functions to encode a number to and decode a number from Gray code.
Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary).
There are many possible Gray codes. The following encodes what is called "binary reflected Gray code."
Encoding (MSB is bit 0, b is binary, g is Gray code):
if b[i-1] = 1
g[i] = not b[i]
else
g[i] = b[i]
Or:
g = b xor (b logically right shifted 1 time)
Decoding (MSB is bit 0, b is binary, g is Gray code):
b[0] = g[0]
for other bits:
b[i] = g[i] xor b[i-1]
Reference
Converting Between Gray and Binary Codes. It includes step-by-step animations.
|
#XBasic
|
XBasic
|
' Gray code
PROGRAM "graycode"
VERSION "0.0001"
DECLARE FUNCTION Entry()
INTERNAL FUNCTION Encode(v&)
INTERNAL FUNCTION Decode(v&)
FUNCTION Entry()
PRINT "decimal binary gray decoded"
FOR i& = 0 TO 31
g& = Encode(i&)
d& = Decode(g&)
PRINT FORMAT$(" ##", i&); " "; BIN$(i&, 5); " "; BIN$(g&, 5);
PRINT " "; BIN$(d&, 5); FORMAT$(" ##", d&)
NEXT i&
END FUNCTION
FUNCTION Encode(v&)
END FUNCTION v& ^ (v& >> 1)
FUNCTION Decode(v&)
result& = 0
DO WHILE v& > 0
result& = result& ^ v&
v& = v& >> 1
LOOP
END FUNCTION result&
END PROGRAM
|
http://rosettacode.org/wiki/Generic_swap
|
Generic swap
|
Task
Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types.
If your solution language is statically typed please describe the way your language provides genericity.
If variables are typed in the given language, it is permissible that the two variables be constrained to having a mutually compatible type, such that each is permitted to hold the value previously stored in the other without a type violation.
That is to say, solutions do not have to be capable of exchanging, say, a string and integer value, if the underlying storage locations are not attributed with types that permit such an exchange.
Generic swap is a task which brings together a few separate issues in programming language semantics.
Dynamically typed languages deal with values in a generic way quite readily, but do not necessarily make it easy to write a function to destructively swap two variables, because this requires indirection upon storage places or upon the syntax designating storage places.
Functional languages, whether static or dynamic, do not necessarily allow a destructive operation such as swapping two variables regardless of their generic capabilities.
Some static languages have difficulties with generic programming due to a lack of support for (Parametric Polymorphism).
Do your best!
|
#Erlang
|
Erlang
|
1> L = [a, 2].
[a,2]
2> lists:reverse(L).
[2,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.
|
#Euphoria
|
Euphoria
|
function aeval( sequence sArr, integer id )
for i = 1 to length( sArr ) do
sArr[ i ] = call_func( id, { sArr[ i ] } )
end for
return sArr
end function
object biggun
function biggest( object elem )
if compare(elem, biggun) > 0 then
biggun = elem
end if
return elem
end function
biggun = 0
object a
a = aeval( {1,1234,62,234,12,34,6}, routine_id("biggest") )
printf( 1, "%d\n", biggun )
sequence s
s = {"antelope", "dog", "cat", "cow", "wolf", "wolverine", "aardvark"}
biggun = "ant"
a = aeval( s, routine_id("biggest") )
printf( 1, "%s\n", {biggun} )
|
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.
|
#Eiffel
|
Eiffel
|
class
APPLICATION
create
make
feature -- Implementation
gcd (x: INTEGER y: INTEGER): INTEGER
do
if y = 0 then
Result := x
else
Result := gcd (y, x \\ y);
end
end
feature {NONE} -- Initialization
make
-- Run application.
do
print (gcd (15, 10))
print ("%N")
end
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).
|
#F.23
|
F#
|
let rec hailstone n = seq {
match n with
| 1 -> yield 1
| n when n % 2 = 0 -> yield n; yield! hailstone (n / 2)
| n -> yield n; yield! hailstone (n * 3 + 1)
}
let hailstone27 = hailstone 27 |> Array.ofSeq
assert (Array.length hailstone27 = 112)
assert (hailstone27.[..3] = [|27;82;41;124|])
assert (hailstone27.[108..] = [|8;4;2;1|])
let maxLen, maxI = Seq.max <| seq { for i in 1..99999 -> Seq.length (hailstone i), i}
printfn "Maximum length %d was found for hailstone(%d)" maxLen maxI
|
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).
|
#R
|
R
|
hamming=function(hamms,limit) {
tmp=hamms
for(h in c(2,3,5)) {
tmp=c(tmp,h*hamms)
}
tmp=unique(tmp[tmp<=limit])
if(length(tmp)>length(hamms)) {
hamms=hamming(tmp,limit)
}
hamms
}
h <- sort(hamming(1,limit=2^31-1))
print(h[1:20])
print(h[length(h)])
|
http://rosettacode.org/wiki/Guess_the_number
|
Guess the number
|
Task
Write a program where the program chooses a number between 1 and 10.
A player is then prompted to enter a guess. If the player guesses wrong, then the prompt appears again until the guess is correct.
When the player has made a successful guess the computer will issue a "Well guessed!" message, and the program exits.
A conditional loop may be used to repeat the guessing until the user is correct.
Related tasks
Bulls and cows
Bulls and cows/Player
Guess the number/With Feedback
Mastermind
|
#Ursa
|
Ursa
|
# Simple number guessing game
decl ursa.util.random random
decl int target guess
set target (int (+ 1 (random.getint 9)))
out "Guess a number between 1 and 10." endl console
while (not (= target guess))
set guess (in int console)
end while
out "That's right!" endl console
|
http://rosettacode.org/wiki/Guess_the_number
|
Guess the number
|
Task
Write a program where the program chooses a number between 1 and 10.
A player is then prompted to enter a guess. If the player guesses wrong, then the prompt appears again until the guess is correct.
When the player has made a successful guess the computer will issue a "Well guessed!" message, and the program exits.
A conditional loop may be used to repeat the guessing until the user is correct.
Related tasks
Bulls and cows
Bulls and cows/Player
Guess the number/With Feedback
Mastermind
|
#Vala
|
Vala
|
int main() {
int x = Random.int_range(1, 10);
stdout.printf("Make a guess (1-10): ");
while(int.parse(stdin.read_line()) != x)
stdout.printf("Wrong! Try again: ");
stdout.printf("Got it!\n");
return 0;
}
|
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)
|
#OCaml
|
OCaml
|
let rec _read_int() =
try read_int()
with _ ->
print_endline "Please give a cardinal numbers.";
(* TODO: what is the correct word? cipher, digit, figure or numeral? *)
_read_int() ;;
let () =
print_endline "Please give a set limits (two integers):";
let a = _read_int()
and b = _read_int() in
let a, b =
if a < b
then (a, b)
else (b, a)
in
Random.self_init();
let target = a + Random.int (b - a) in
Printf.printf "I have choosen a number between %d and %d\n%!" a b;
print_endline "Please guess it!";
let rec loop () =
let guess = _read_int() in
if guess = target then
begin
print_endline "The guess was equal to the target.\nCongratulation!";
exit 0
end;
if guess < a || guess > b then
print_endline "The input was inappropriate."
else if guess > target then
print_endline "The guess was higher than the target."
else if guess < target then
print_endline "The guess was less than the target.";
loop ()
in
loop ()
|
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
|
#Oz
|
Oz
|
functor
import
System
define
fun {IsHappy N}
{IsHappy2 N nil}
end
fun {IsHappy2 N Seen}
if N == 1 then true
elseif {Member N Seen} then false
else
Next = {Sum {Map {Digits N} Square}}
in
{IsHappy2 Next N|Seen}
end
end
fun {Sum Xs}
{FoldL Xs Number.'+' 0}
end
fun {Digits N}
{Map {Int.toString N} fun {$ D} D - &0 end}
end
fun {Square N} N*N end
fun lazy {Nat I}
I|{Nat I+1}
end
%% List.filter is eager. But we need a lazy Filter:
fun lazy {LFilter Xs P}
case Xs of X|Xr andthen {P X} then X|{LFilter Xr P}
[] _|Xr then {LFilter Xr P}
[] nil then nil
end
end
HappyNumbers = {LFilter {Nat 1} IsHappy}
in
{System.show {List.take HappyNumbers 8}}
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
|
#Julia
|
Julia
|
println("Hello world!")
|
http://rosettacode.org/wiki/Hello_world/Graphical
|
Hello world/Graphical
|
Task
Display the string Goodbye, World! on a GUI object (alert box, plain window, text area, etc.).
Related task
Hello world/Text
|
#Vala
|
Vala
|
#!/usr/local/bin/vala --pkg gtk+-3.0
using Gtk;
void main(string[] args) {
Gtk.init(ref args);
var window = new Window();
window.title = "Goodbye, world!";
window.border_width = 10;
window.window_position = WindowPosition.CENTER;
window.set_default_size(350, 70);
window.destroy.connect(Gtk.main_quit);
var label = new Label("Goodbye, world!");
window.add(label);
window.show_all();
Gtk.main();
}
|
http://rosettacode.org/wiki/Gray_code
|
Gray code
|
Gray code
Karnaugh maps
Create functions to encode a number to and decode a number from Gray code.
Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary).
There are many possible Gray codes. The following encodes what is called "binary reflected Gray code."
Encoding (MSB is bit 0, b is binary, g is Gray code):
if b[i-1] = 1
g[i] = not b[i]
else
g[i] = b[i]
Or:
g = b xor (b logically right shifted 1 time)
Decoding (MSB is bit 0, b is binary, g is Gray code):
b[0] = g[0]
for other bits:
b[i] = g[i] xor b[i-1]
Reference
Converting Between Gray and Binary Codes. It includes step-by-step animations.
|
#XPL0
|
XPL0
|
include c:\cxpl\codes; \intrinsic 'code' declarations
func Gray2Bin(N); \Convert N from Gray code to binary
int N;
int S;
[S:= 1;
repeat N:= N>>S | N;
S:= S<<1;
until S=32;
return N;
]; \Gray2Bin
func Bin2Gray(N); \Convert N from binary to Gray code
int N;
return N>>1 | N;
proc BinOut(N); \Output N in binary
int N;
int R;
[R:= N&1;
N:= N>>1;
if N then BinOut(N);
ChOut(0, R+^0);
]; \BinOut
int N, G;
[for N:= 0 to 31 do
[BinOut(N); ChOut(0, 9\tab\);
G:= Bin2Gray(N);
BinOut(G); ChOut(0, 9\tab\);
BinOut(Gray2Bin(G)); CrLf(0);
];
]
|
http://rosettacode.org/wiki/Gray_code
|
Gray code
|
Gray code
Karnaugh maps
Create functions to encode a number to and decode a number from Gray code.
Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary).
There are many possible Gray codes. The following encodes what is called "binary reflected Gray code."
Encoding (MSB is bit 0, b is binary, g is Gray code):
if b[i-1] = 1
g[i] = not b[i]
else
g[i] = b[i]
Or:
g = b xor (b logically right shifted 1 time)
Decoding (MSB is bit 0, b is binary, g is Gray code):
b[0] = g[0]
for other bits:
b[i] = g[i] xor b[i-1]
Reference
Converting Between Gray and Binary Codes. It includes step-by-step animations.
|
#zkl
|
zkl
|
fcn grayEncode(n){ n.bitXor(n.shiftRight(1)) }
fcn grayDecode(g){ b:=g; while(g/=2){ b=b.bitXor(g) } b }
|
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!
|
#Euphoria
|
Euphoria
|
include std/console.e -- for display
object x = 3.14159
object y = "Rosettacode"
{y,x} = {x,y}
display("x is now []",{x})
display("y is now []",{y})
|
http://rosettacode.org/wiki/Greatest_element_of_a_list
|
Greatest element of a list
|
Task
Create a function that returns the maximum value in a provided set of values,
where the number of values may not be known until run-time.
|
#Excel
|
Excel
|
=MAX(3;2;1;4;5;23;1;2)
|
http://rosettacode.org/wiki/Greatest_element_of_a_list
|
Greatest element of a list
|
Task
Create a function that returns the maximum value in a provided set of values,
where the number of values may not be known until run-time.
|
#F.23
|
F#
|
let N = System.Random()
let G = List.init 10 (fun _->N.Next())
List.iter (printf "%d ") G
printfn "\nMax value of list is %d" (List.max G)
|
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.
|
#Elena
|
Elena
|
import system'math;
import extensions;
gcd(a,b)
{
var i := a;
var j := b;
while(j != 0)
{
var tmp := i;
i := j;
j := tmp.mod(j)
};
^ i
}
printGCD(a,b)
{
console.printLineFormatted("GCD of {0} and {1} is {2}", a, b, gcd(a,b))
}
public program()
{
printGCD(1,1);
printGCD(1,10);
printGCD(10,100);
printGCD(5,50);
printGCD(8,24);
printGCD(36,17);
printGCD(36,18);
printGCD(36,19);
printGCD(36,33);
}
|
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).
|
#Factor
|
Factor
|
! rosetta/hailstone/hailstone.factor
USING: arrays io kernel math math.ranges prettyprint sequences vectors ;
IN: rosetta.hailstone
: hailstone ( n -- seq )
[ 1vector ] keep
[ dup 1 number= ]
[
dup even? [ 2 / ] [ 3 * 1 + ] if
2dup swap push
] until
drop ;
<PRIVATE
: main ( -- )
27 hailstone dup dup
"The hailstone sequence from 27:" print
" has length " write length .
" starts with " write 4 head [ unparse ] map ", " join print
" ends with " write 4 tail* [ unparse ] map ", " join print
! Maps n => { length n }, and reduces to longest Hailstone sequence.
1 100000 [a,b)
[ [ hailstone length ] keep 2array ]
[ [ [ first ] bi@ > ] most ] map-reduce
first2
"The hailstone sequence from " write pprint
" has length " write pprint "." print ;
PRIVATE>
MAIN: main
|
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).
|
#Racket
|
Racket
|
#lang racket
(require racket/stream)
(define first stream-first)
(define rest stream-rest)
(define (merge s1 s2)
(define x1 (first s1))
(define x2 (first s2))
(cond [(= x1 x2) (merge s1 (rest s2))]
[(< x1 x2) (stream-cons x1 (merge (rest s1) s2))]
[else (stream-cons x2 (merge s1 (rest s2)))]))
(define (mult k) (λ(x) (* x k)))
(define hamming
(stream-cons
1 (merge (stream-map (mult 2) hamming)
(merge (stream-map (mult 3) hamming)
(stream-map (mult 5) hamming)))))
(for/list ([i 20] [x hamming]) x)
(stream-ref hamming 1690)
(stream-ref hamming 999999)
|
http://rosettacode.org/wiki/Guess_the_number
|
Guess the number
|
Task
Write a program where the program chooses a number between 1 and 10.
A player is then prompted to enter a guess. If the player guesses wrong, then the prompt appears again until the guess is correct.
When the player has made a successful guess the computer will issue a "Well guessed!" message, and the program exits.
A conditional loop may be used to repeat the guessing until the user is correct.
Related tasks
Bulls and cows
Bulls and cows/Player
Guess the number/With Feedback
Mastermind
|
#VBA
|
VBA
|
Sub GuessTheNumber()
Dim NbComputer As Integer, NbPlayer As Integer
Randomize Timer
NbComputer = Int((Rnd * 10) + 1)
Do
NbPlayer = Application.InputBox("Choose a number between 1 and 10 : ", "Enter your guess", Type:=1)
Loop While NbComputer <> NbPlayer
MsgBox "Well guessed!"
End Sub
|
http://rosettacode.org/wiki/Guess_the_number
|
Guess the number
|
Task
Write a program where the program chooses a number between 1 and 10.
A player is then prompted to enter a guess. If the player guesses wrong, then the prompt appears again until the guess is correct.
When the player has made a successful guess the computer will issue a "Well guessed!" message, and the program exits.
A conditional loop may be used to repeat the guessing until the user is correct.
Related tasks
Bulls and cows
Bulls and cows/Player
Guess the number/With Feedback
Mastermind
|
#VBScript
|
VBScript
|
randomize
MyNum=Int(rnd*10)+1
Do
x=x+1
YourGuess=InputBox("Enter A number from 1 to 10")
If not Isnumeric(YourGuess) then
msgbox YourGuess &" is not numeric. Try again."
ElseIf CInt(YourGuess)>10 or CInt(YourGuess)<1 then
msgbox YourGuess &" is not between 1 and 10. Try Again."
ElseIf CInt(YourGuess)=CInt(MyNum) then
MsgBox "Well Guessed!"
wscript.quit
ElseIf Cint(YourGuess)<>CInt(Mynum) then
MsgBox "Nope. Try again."
end If
if x > 20 then
msgbox "I take pity on you"
wscript.quit
end if
loop
|
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)
|
#Octave
|
Octave
|
function guess_a_number(low,high)
% Guess a number (with feedback)
% http://rosettacode.org/wiki/Guess_the_number/With_feedback
if nargin<1,
low=1;
end;
if nargin<2,
high=10;
end;
n = floor(rand(1)*(high-low+1))+low;
[guess,state] = str2num(input(sprintf('Guess a number between %i and %i: ',low,high),'s'));
while (~state || guess~=n)
if guess < n,
g = input('to low, guess again: ','s');
[guess, state] = str2num(g);
elseif guess > n,
g = input('to high, guess again: ','s');
[guess, state] = str2num(g);
end;
while ~state
g = input('invalid input, guess again: ','s');
[guess, state] = str2num(g);
end
end
disp('Well guessed!')
|
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
|
#PARI.2FGP
|
PARI/GP
|
H=[1,7,10,13,19,23,28,31,32,44,49,68,70,79,82,86,91,94,97,100,103,109,129,130,133,139,167,176,188,190,192,193,203,208,219,226,230,236,239];
isHappy(n)={
if(n<262,
setsearch(H,n)>0
,
n=eval(Vec(Str(n)));
isHappy(sum(i=1,#n,n[i]^2))
)
};
select(isHappy, vector(31,i,i))
|
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
|
#K
|
K
|
"Hello world!"
|
http://rosettacode.org/wiki/Hello_world/Graphical
|
Hello world/Graphical
|
Task
Display the string Goodbye, World! on a GUI object (alert box, plain window, text area, etc.).
Related task
Hello world/Text
|
#VBA
|
VBA
|
Public Sub hello_world_gui()
MsgBox "Goodbye, World!"
End Sub
|
http://rosettacode.org/wiki/Hello_world/Graphical
|
Hello world/Graphical
|
Task
Display the string Goodbye, World! on a GUI object (alert box, plain window, text area, etc.).
Related task
Hello world/Text
|
#VBScript
|
VBScript
|
MsgBox("Goodbye, 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!
|
#F.23
|
F#
|
let swap (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.
|
#Factor
|
Factor
|
: supremum ( seq -- elt ) [ ] [ max ] map-reduce ;
|
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.
|
#Fancy
|
Fancy
|
[1,-2,2,4,6,-4,-1,5] max println # => 6
|
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.
|
#Elixir
|
Elixir
|
defmodule RC do
def gcd(a,0), do: abs(a)
def gcd(a,b), do: gcd(b, rem(a,b))
end
IO.puts RC.gcd(1071, 1029)
IO.puts RC.gcd(3528, 3780)
|
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.
|
#Emacs_Lisp
|
Emacs Lisp
|
(defun gcd (a b)
(cond
((< a b) (gcd a (- b a)))
((> a b) (gcd (- a b) b))
(t 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).
|
#FALSE
|
FALSE
|
[$1&$[%3*1+0~]?~[2/]?]n:
[[$." "$1>][n;!]#%]s:
[1\[$1>][\1+\n;!]#%]c:
27s;! 27c;!."
"
0m:0f:
1[$100000\>][$c;!$m;>[m:$f:0]?%1+]#%
f;." has hailstone sequence length "m;.
|
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).
|
#Raku
|
Raku
|
my $limit = 32;
sub powers_of ($radix) { 1, |[\*] $radix xx * }
my @hammings =
( powers_of(2)[^ $limit ] X*
powers_of(3)[^($limit * 2/3)] X*
powers_of(5)[^($limit * 1/2)]
).sort;
say @hammings[^20];
say @hammings[1690]; # zero indexed
|
http://rosettacode.org/wiki/Guess_the_number
|
Guess the number
|
Task
Write a program where the program chooses a number between 1 and 10.
A player is then prompted to enter a guess. If the player guesses wrong, then the prompt appears again until the guess is correct.
When the player has made a successful guess the computer will issue a "Well guessed!" message, and the program exits.
A conditional loop may be used to repeat the guessing until the user is correct.
Related tasks
Bulls and cows
Bulls and cows/Player
Guess the number/With Feedback
Mastermind
|
#Visual_Basic_.NET
|
Visual Basic .NET
|
Module Guess_the_Number
Sub Main()
Dim random As New Random()
Dim secretNum As Integer = random.Next(10) + 1
Dim gameOver As Boolean = False
Console.WriteLine("I am thinking of a number from 1 to 10. Can you guess it?")
Do
Dim guessNum As Integer
Console.Write("Enter your guess: ")
If Not Integer.TryParse(Console.ReadLine(), guessNum) Then
Console.WriteLine("You should enter a number from 1 to 10. Try again!")
Continue Do
End If
If guessNum = secretNum Then
Console.WriteLine("Well guessed!")
gameOver = True
Else
Console.WriteLine("Incorrect. Try again!")
End If
Loop Until gameOver
End Sub
End Module
|
http://rosettacode.org/wiki/Guess_the_number
|
Guess the number
|
Task
Write a program where the program chooses a number between 1 and 10.
A player is then prompted to enter a guess. If the player guesses wrong, then the prompt appears again until the guess is correct.
When the player has made a successful guess the computer will issue a "Well guessed!" message, and the program exits.
A conditional loop may be used to repeat the guessing until the user is correct.
Related tasks
Bulls and cows
Bulls and cows/Player
Guess the number/With Feedback
Mastermind
|
#Vlang
|
Vlang
|
import rand
import rand.seed
import os
fn main() {
seed_array := seed.time_seed_array(2)
rand.seed(seed_array)
num := rand.intn(10) + 1 // Random number 1-10
for {
print('Please guess a number from 1-10 and press <Enter>: ')
guess := os.get_line()
if guess.int() == num {
println("Well guessed! '$guess' is correct.")
return
} else {
println("'$guess' is Incorrect. Try again.")
}
}
}
|
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)
|
#Oforth
|
Oforth
|
import: console
: guessNumber(a, b)
| n g |
b a - rand a + 1- ->n
begin
"Guess a number between" . a . "and" . b . ":" .
while(System.Console askln asInteger dup -> g isNull) [ "Not a number " println ]
g n == ifTrue: [ "You found it !" .cr return ]
g n < ifTrue: [ "Less" ] else: [ "Greater" ] . "than the target" .cr
again ;
|
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)
|
#Ol
|
Ol
|
(import (otus random!))
(define from 0)
(define to 100)
(define number (+ from (rand! (+ from to 1))))
(let loop ()
(for-each display `("Pick a number from " ,from " through " ,to ": "))
(let ((guess (read)))
(cond
((not (number? guess))
(print "Not a number!")
(loop))
((or (< guess from)
(< to guess))
(print "Out of range!")
(loop))
((< guess number)
(print "Too low!")
(loop))
((> guess number)
(print "Too high!")
(loop))
((= guess number)
(print "Well guessed!")))))
|
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
|
#Pascal
|
Pascal
|
Program HappyNumbers (output);
uses
Math;
function find(n: integer; cache: array of integer): boolean;
var
i: integer;
begin
find := false;
for i := low(cache) to high(cache) do
if cache[i] = n then
find := true;
end;
function is_happy(n: integer): boolean;
var
cache: array of integer;
sum: integer;
begin
setlength(cache, 1);
repeat
sum := 0;
while n > 0 do
begin
sum := sum + (n mod 10)**2;
n := n div 10;
end;
if sum = 1 then
begin
is_happy := true;
break;
end;
if find(sum, cache) then
begin
is_happy := false;
break;
end;
n := sum;
cache[high(cache)]:= sum;
setlength(cache, length(cache)+1);
until false;
end;
var
n, count: integer;
begin
n := 1;
count := 0;
while count < 8 do
begin
if is_happy(n) then
begin
inc(count);
write(n, ' ');
end;
inc(n);
end;
writeln;
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
|
#Kabap
|
Kabap
|
return = "Hello world!";
|
http://rosettacode.org/wiki/Hello_world/Graphical
|
Hello world/Graphical
|
Task
Display the string Goodbye, World! on a GUI object (alert box, plain window, text area, etc.).
Related task
Hello world/Text
|
#Vedit_macro_language
|
Vedit macro language
|
Statline_Message("Goodbye, World!")
|
http://rosettacode.org/wiki/Hello_world/Graphical
|
Hello world/Graphical
|
Task
Display the string Goodbye, World! on a GUI object (alert box, plain window, text area, etc.).
Related task
Hello world/Text
|
#Visual_Basic
|
Visual Basic
|
Sub Main()
MsgBox "Goodbye, World!"
End Sub
|
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!
|
#Factor
|
Factor
|
swap
|
http://rosettacode.org/wiki/Greatest_element_of_a_list
|
Greatest element of a list
|
Task
Create a function that returns the maximum value in a provided set of values,
where the number of values may not be known until run-time.
|
#Fantom
|
Fantom
|
class Greatest
{
public static Void main ()
{
Int[] values := [1,2,3,4,5,6,7,8,9]
Int greatest := values.max
echo (greatest)
}
}
|
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.
|
#Forth
|
Forth
|
: array-max ( addr len -- max )
dup 0= if nip exit then
over @ rot cell+ rot 1-
cells bounds ?do i @ max cell +loop ;
: stack-max ( n ... m count -- max ) 1 ?do max loop ;
|
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.
|
#Erlang
|
Erlang
|
% Implemented by Arjun Sunel
-module(gcd).
-export([main/0]).
main() ->gcd(-36,4).
gcd(A, 0) -> A;
gcd(A, B) -> gcd(B, A rem 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).
|
#Fermat
|
Fermat
|
Array g[2]
Func Collatz(n, d) =
{Runs the Collatz procedure for the number n and returns the number of steps.}
{If d is nonzero, prints the terms in the sequence.}
steps := 1;
while n>1 do
if n|2=0 then n:=n/2 else n:=3n+1 fi;
if d then !!n fi;
steps := steps + 1
od;
steps.
Function LongestTo(n) =
{Finds the number up to n for which the Collatz algorithm takes the most number of steps.}
{The result is stored in the array [g]: g[1] is the number, g[2] is how many steps it takes.}
champ:=0;
record:=0;
for i = 1, n do
q:=Collatz(i, 0);
if q > record then
champ:=i; record:=q; fi;
od;
g[1]:=champ;
g[2]:=record;
.
|
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).
|
#Raven
|
Raven
|
define hamming use $limit
[ ] as $h
1 $h 0 set
2 as $x2 3 as $x3 5 as $x5
0 as $i 0 as $j 0 as $k
1 $limit 1 + 1 range each as $n
$x3 $x5 min $x2 min $h $n set
$h $n get $x2 = if
$i 1 + as $i
$h $i get 2 * as $x2
$h $n get $x3 = if
$j 1 + as $j
$h $j get 3 * as $x3
$h $n get $x5 = if
$k 1 + as $k
$h $k get 5 * as $x5
$h $limit 1 - get
1 21 1 range each as $lim
$lim hamming print " " print
"\n" print
"Hamming(1691) is: " print 1691 hamming print "\n" print
# Raven can't handle > 2^31 using integers
#
#"Hamming(1000000) is: " print 1000000 hamming print "\n" print
|
http://rosettacode.org/wiki/Guess_the_number
|
Guess the number
|
Task
Write a program where the program chooses a number between 1 and 10.
A player is then prompted to enter a guess. If the player guesses wrong, then the prompt appears again until the guess is correct.
When the player has made a successful guess the computer will issue a "Well guessed!" message, and the program exits.
A conditional loop may be used to repeat the guessing until the user is correct.
Related tasks
Bulls and cows
Bulls and cows/Player
Guess the number/With Feedback
Mastermind
|
#WebAssembly
|
WebAssembly
|
(module
(import "wasi_unstable" "fd_read"
(func $fd_read (param i32 i32 i32 i32) (result i32)))
(import "wasi_unstable" "fd_write"
(func $fd_write (param i32 i32 i32 i32) (result i32)))
(import "wasi_unstable" "random_get"
(func $random_get (param i32 i32) (result i32)))
(memory 1) (export "memory" (memory 0))
;; memory usage:
;; 0-7: temp IO Vector used with WASI functions
;; 8-24: temp buffer used for reading numbers
;; 100-: string data
;; string constants
(data (i32.const 100) "Guess a number between 1 and 10.\n")
(data (i32.const 200) "Well guessed!\n")
;; function to print a null-terminated string at the given address
;; (assumes use of an IOVector at address 0)
(func $print_cstr (param $strAddr i32)
(local $charPos i32)
;; store the data address into our IO vector (address 0)
i32.const 0 local.get $strAddr i32.store
;; find the null terminator at the end of the string
local.get $strAddr local.set $charPos
block $loop_break
loop $LOOP
;; get the character at charPos
local.get $charPos i32.load
;; if it is equal to zero, break out of the loop
i32.eqz if br $loop_break end
;; otherwise, increment and loop
local.get $charPos i32.const 1 i32.add local.set $charPos
br $LOOP
end
end
;; from that, compute the length of the string for our IOVector
i32.const 4 ;; (address of string length in the IOVector)
local.get $charPos local.get $strAddr i32.sub
i32.store
;; now call $fd_write to actually write to stdout
i32.const 1 ;; 1 for stdout
i32.const 0 i32.const 1 ;; 1 IOVector at address 0
i32.const 0 ;; where to stuff the number of bytes written
call $fd_write
drop ;; (drop the result value)
)
;; function to read a number
;; (assumes use of an IOVector at address 0,
;; and 16-character buffer at address 8)
(func $input_i32 (result i32)
(local $ptr i32)
(local $n i32)
(local $result i32)
;; prepare our IOVector to point to the buffer
i32.const 0 i32.const 8 i32.store ;; (address of buffer)
i32.const 4 i32.const 16 i32.store ;; (size of buffer)
i32.const 0 ;; 0 for stdin
i32.const 0 i32.const 1 ;; 1 IOVector at address 0
i32.const 4 ;; where to stuff the number of bytes read
call $fd_read drop
;; Convert that to a number!
;; loop over characters in the string until we hit something < '0'.
i32.const 8 local.set $ptr
block $LOOP_BREAK
loop $LOOP
;; get value of current digit
;; (we assume all positive integers for this task)
local.get $ptr i32.load8_u
i32.const 48 i32.sub ;; (subtract 48, ASCII value of '0')
local.tee $n
;; bail out if < 0
i32.const 0 i32.lt_s br_if $LOOP_BREAK
;; multiply current number by 10, and add new number
local.get $result i32.const 10 i32.mul
local.get $n i32.add
local.set $result
;; increment and loop
local.get $ptr i32.const 1 i32.add local.set $ptr
br $LOOP
end
end
local.get $result
)
;; function to get a random i32
;; (assumes use of temporary space at address 0)
(func $random_i32 (result i32)
i32.const 0 i32.const 4 call $random_get drop
i32.const 0 i32.load
)
(func $main (export "_start")
(local $trueNumber i32)
;; get a random integer, then take that (unsigned) mod 10
call $random_i32 i32.const 10 i32.rem_u
local.set $trueNumber
loop $LOOP
;; print prompt
i32.const 100 call $print_cstr
;; input a guess
call $input_i32
;; if correct, print message and we're done
local.get $trueNumber i32.eq if
i32.const 200 call $print_cstr
return
end
br $LOOP
end
)
)
|
http://rosettacode.org/wiki/Guess_the_number
|
Guess the number
|
Task
Write a program where the program chooses a number between 1 and 10.
A player is then prompted to enter a guess. If the player guesses wrong, then the prompt appears again until the guess is correct.
When the player has made a successful guess the computer will issue a "Well guessed!" message, and the program exits.
A conditional loop may be used to repeat the guessing until the user is correct.
Related tasks
Bulls and cows
Bulls and cows/Player
Guess the number/With Feedback
Mastermind
|
#Wee_Basic
|
Wee Basic
|
let mnnumber=1
let mxnumber=10
let number=mnnumber
let keycode=0
let guessed=0
print 1 "Press any key so the computer can generate a random number for you to guess."
while keycode=0
let number=number=1
let keycode=key()
if number=mxnumber+1
let number=mnnumber
endif
wend
print 1 "Guess the number. It is between "+mnnumber+"and "+mxnumber
while guessed=0
input guess
if guess=number
print 1 "Well done! You guessed the correct number."
let guessed=1
else
print 1 "You guessed the incorrect number. Please try again."
endif
wend
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)
|
#ooRexx
|
ooRexx
|
Select instead of a series of If's
simple comparison instead of strict
different indentations.
entering ? shows the number we are looking for
|
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)
|
#PARI.2FGP
|
PARI/GP
|
guess_the_number(N=10)={
a=random(N);
print("guess the number between 0 and "N);
for(x=1,N,
if(x>1,
if(b>a,
print("guess again lower")
,
print("guess again higher")
);
b=input();
if(b==a,break())
);
print("You guessed it correctly")
};
|
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
|
#Perl
|
Perl
|
use List::Util qw(sum);
sub ishappy {
my $s = shift;
while ($s > 6 && $s != 89) {
$s = sum(map { $_*$_ } split(//,$s));
}
$s == 1;
}
my $n = 0;
print join(" ", map { 1 until ishappy(++$n); $n; } 1..8), "\n";
|
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
|
#Kaya
|
Kaya
|
program hello;
Void main() {
// My first program!
putStrLn("Hello world!");
}
|
http://rosettacode.org/wiki/Hello_world/Graphical
|
Hello world/Graphical
|
Task
Display the string Goodbye, World! on a GUI object (alert box, plain window, text area, etc.).
Related task
Hello world/Text
|
#Visual_Basic_.NET
|
Visual Basic .NET
|
Imports System.Windows.Forms
Module GoodbyeWorld
Sub Main()
Messagebox.Show("Goodbye, World!")
End Sub
End Module
|
http://rosettacode.org/wiki/Hello_world/Graphical
|
Hello world/Graphical
|
Task
Display the string Goodbye, World! on a GUI object (alert box, plain window, text area, etc.).
Related task
Hello world/Text
|
#Visual_FoxPro
|
Visual FoxPro
|
* Version 1:
MESSAGEBOX("Goodbye, World!")
* Version 2:
? "Goodbye, 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!
|
#Falcon
|
Falcon
|
a = 1
b = 2
a,b = arr = 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.
|
#Fortran
|
Fortran
|
program test_maxval
integer,dimension(5),parameter :: x = [10,100,7,1,2]
real,dimension(5),parameter :: y = [5.0,60.0,1.0,678.0,0.0]
write(*,'(I5)') maxval(x)
write(*,'(F5.1)') maxval(y)
end program test_maxval
|
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.
|
#ERRE
|
ERRE
|
PROGRAM EUCLIDE
! calculate G.C.D. between two integer numbers
! using Euclidean algorithm
!VAR J%,K%,MCD%,A%,B%
BEGIN
PRINT(CHR$(12);"Input two numbers : ";) !CHR$(147) in C-64 version
INPUT(J%,K%)
A%=J% B%=K%
WHILE A%<>B% DO
IF A%>B%
THEN
A%=A%-B%
ELSE
B%=B%-A%
END IF
END WHILE
MCD%=A%
PRINT("G.C.D. between";J%;"and";K%;"is";MCD%)
END PROGRAM
|
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).
|
#Forth
|
Forth
|
: hail-next ( n -- n )
dup 1 and if 3 * 1+ else 2/ then ;
: .hail ( n -- )
begin dup . dup 1 > while hail-next repeat drop ;
: hail-len ( n -- n )
1 begin over 1 > while swap hail-next swap 1+ repeat nip ;
27 hail-len . cr
27 .hail cr
: longest-hail ( max -- )
0 0 rot 1+ 1 do ( n length )
i hail-len 2dup < if
nip nip i swap
else drop then
loop
swap . ." has hailstone sequence length " . ;
100000 longest-hail
|
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).
|
#REXX
|
REXX
|
/*REXX program computes Hamming numbers: 1 ──► 20, # 1691, and the one millionth. */
numeric digits 100 /*ensure enough decimal digits. */
call hamming 1, 20 /*show the 1st ──► twentieth Hamming #s*/
call hamming 1691 /*show the 1,691st Hamming number. */
call hamming 1000000 /*show the 1 millionth Hamming number.*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
hamming: procedure; parse arg x,y; if y=='' then y= x; w= length(y)
#2= 1; #3= 1; #5= 1; @.= 0; @.1= 1
do n=2 for y-1
@.n= min(2*@.#2, 3*@.#3, 5*@.#5) /*pick the minimum of 3 Hamming numbers*/
if 2*@.#2 == @.n then #2= #2 + 1 /*number already defined? Use next #. */
if 3*@.#3 == @.n then #3= #3 + 1 /* " " " " " " */
if 5*@.#5 == @.n then #5= #5 + 1 /* " " " " " " */
end /*n*/ /* [↑] maybe assign next 3 Hamming#s. */
do j=x to y; say 'Hamming('right(j, w)") =" @.j
end /*j*/
say right( 'length of last Hamming number =' length(@.y), 70); say
return
|
http://rosettacode.org/wiki/Guess_the_number
|
Guess the number
|
Task
Write a program where the program chooses a number between 1 and 10.
A player is then prompted to enter a guess. If the player guesses wrong, then the prompt appears again until the guess is correct.
When the player has made a successful guess the computer will issue a "Well guessed!" message, and the program exits.
A conditional loop may be used to repeat the guessing until the user is correct.
Related tasks
Bulls and cows
Bulls and cows/Player
Guess the number/With Feedback
Mastermind
|
#Wortel
|
Wortel
|
@let {
num 10Wc
guess 0
[
@while != guess num
:guess !prompt "Guess the number between 1 and 10 inclusive"
!alert "Congratulations!\nThe number was {num}."
]
}
|
http://rosettacode.org/wiki/Guess_the_number
|
Guess the number
|
Task
Write a program where the program chooses a number between 1 and 10.
A player is then prompted to enter a guess. If the player guesses wrong, then the prompt appears again until the guess is correct.
When the player has made a successful guess the computer will issue a "Well guessed!" message, and the program exits.
A conditional loop may be used to repeat the guessing until the user is correct.
Related tasks
Bulls and cows
Bulls and cows/Player
Guess the number/With Feedback
Mastermind
|
#Wren
|
Wren
|
import "io" for Stdin, Stdout
import "random" for Random
var rand = Random.new()
var n = rand.int(1, 11) // computer number from 1..10 inclusive
while (true) {
System.write("Your guess 1-10 : ")
Stdout.flush()
var guess = Num.fromString(Stdin.readLine())
if (n == guess) {
System.print("Well guessed!")
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)
|
#Pascal
|
Pascal
|
sub prompt {
my $prompt = shift;
while (1) {
print "\n", $prompt, ": ";
# type ^D, q, quit, quagmire, etc to quit
defined($_ = <STDIN>) and !/^\s*q/ or exit;
return $_ if /^\s*\d+\s*$/s;
$prompt = "Please give a non-negative integer";
}
}
my $tgt = int(rand prompt("Hola! Please tell me the upper bound") + 1);
my $tries = 1;
$tries++, print "You guessed too ", ($_ == -1 ? "high" : "low"), ".\n"
while ($_ = $tgt <=> prompt "Your guess");
print "Correct! You guessed it after $tries tries.\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
|
#Phix
|
Phix
|
function is_happy(integer n)
sequence seen = {}
while n>1 do
seen &= n
integer k = 0
while n>0 do
k += power(remainder(n,10),2)
n = floor(n/10)
end while
n = k
if find(n,seen) then
return false
end if
end while
return true
end function
integer n = 1
sequence s = {}
while length(s)<8 do
if is_happy(n) then
s &= n
end if
n += 1
end while
?s
|
http://rosettacode.org/wiki/Hello_world/Text
|
Hello world/Text
|
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
|
#Kdf9_Usercode
|
Kdf9 Usercode
|
V2; W0;
RESTART; J999; J999;
PROGRAM; (main program);
V0 = Q0/AV1/AV2;
V1 = B0750064554545700; ("Hello" in Flexowriter code);
V2 = B0767065762544477; ("World" in Flexowriter code);
V0; =Q9; POAQ9; (write "Hello World" to Flexowriter);
999; OUT;
FINISH;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.