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/Sum_and_product_puzzle
Sum and product puzzle
Task[edit] Solve the "Impossible Puzzle": X and Y are two different whole numbers greater than 1. Their sum is no greater than 100, and Y is greater than X. S and P are two mathematicians (and consequently perfect logicians); S knows the sum X+Y and P knows the product X*Y. Both S and P know all the information in this paragraph. The following conversation occurs: S says "P does not know X and Y." P says "Now I know X and Y." S says "Now I also know X and Y!" What are X and Y? Guidance It can be hard to wrap one's head around what the three lines of dialog between S (the "sum guy") and P (the "product guy") convey about the values of X and Y. So for your convenience, here's a break-down: Quote Implied fact 1) S says "P does not know X and Y." For every possible sum decomposition of the number X+Y, the product has in turn more than one product decomposition. 2) P says "Now I know X and Y." The number X*Y has only one product decomposition for which fact 1 is true. 3) S says "Now I also know X and Y." The number X+Y has only one sum decomposition for which fact 2 is true. Terminology: "sum decomposition" of a number = Any pair of positive integers (A, B) so that A+B equals the number. Here, with the additional constraint 2 ≤ A < B. "product decomposition" of a number = Any pair of positive integers (A, B) so that A*B equals the number. Here, with the additional constraint 2 ≤ A < B. Your program can solve the puzzle by considering all possible pairs (X, Y) in the range 2 ≤ X < Y ≤ 98, and then successively eliminating candidates based on the three facts. It turns out only one solution remains! See the Python example for an implementation that uses this approach with a few optimizations. See also   Wikipedia:   Sum and Product Puzzle
#Python
Python
#!/usr/bin/env python   from collections import Counter   def decompose_sum(s): return [(a,s-a) for a in range(2,int(s/2+1))]   # Generate all possible pairs all_pairs = set((a,b) for a in range(2,100) for b in range(a+1,100) if a+b<100)   # Fact 1 --> Select pairs for which all sum decompositions have non-unique product product_counts = Counter(c*d for c,d in all_pairs) unique_products = set((a,b) for a,b in all_pairs if product_counts[a*b]==1) s_pairs = [(a,b) for a,b in all_pairs if all((x,y) not in unique_products for (x,y) in decompose_sum(a+b))]   # Fact 2 --> Select pairs for which the product is unique product_counts = Counter(c*d for c,d in s_pairs) p_pairs = [(a,b) for a,b in s_pairs if product_counts[a*b]==1]   # Fact 3 --> Select pairs for which the sum is unique sum_counts = Counter(c+d for c,d in p_pairs) final_pairs = [(a,b) for a,b in p_pairs if sum_counts[a+b]==1]   print(final_pairs)
http://rosettacode.org/wiki/Temperature_conversion
Temperature conversion
There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones: Kelvin, Celsius, Fahrenheit, and Rankine. The Celsius and Kelvin scales have the same magnitude, but different null points. 0 degrees Celsius corresponds to 273.15 kelvin. 0 kelvin is absolute zero. The Fahrenheit and Rankine scales also have the same magnitude, but different null points. 0 degrees Fahrenheit corresponds to 459.67 degrees Rankine. 0 degrees Rankine is absolute zero. The Celsius/Kelvin and Fahrenheit/Rankine scales have a ratio of 5 : 9. Task Write code that accepts a value of kelvin, converts it to values of the three other scales, and prints the result. Example K 21.00 C -252.15 F -421.87 R 37.80
#XLISP
XLISP
(DEFUN CONVERT-TEMPERATURE () (SETQ *FLONUM-FORMAT* "%.2f") (DISPLAY "Enter a temperature in Kelvin.") (NEWLINE) (DISPLAY "> ") (DEFINE K (READ)) (DISPLAY `(K = ,K)) (NEWLINE) (DISPLAY `(C = ,(- K 273.15))) (NEWLINE) (DISPLAY `(F = ,(- (* K 1.8) 459.67))) (NEWLINE) (DISPLAY `(R = ,(* K 1.8))))
http://rosettacode.org/wiki/Temperature_conversion
Temperature conversion
There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones: Kelvin, Celsius, Fahrenheit, and Rankine. The Celsius and Kelvin scales have the same magnitude, but different null points. 0 degrees Celsius corresponds to 273.15 kelvin. 0 kelvin is absolute zero. The Fahrenheit and Rankine scales also have the same magnitude, but different null points. 0 degrees Fahrenheit corresponds to 459.67 degrees Rankine. 0 degrees Rankine is absolute zero. The Celsius/Kelvin and Fahrenheit/Rankine scales have a ratio of 5 : 9. Task Write code that accepts a value of kelvin, converts it to values of the three other scales, and prints the result. Example K 21.00 C -252.15 F -421.87 R 37.80
#XPL0
XPL0
include c:\cxpl\codes; real K, C, F, R; [ChOut(0, ^K); K:= RlIn(0); C:= K - 273.15; ChOut(0, ^C); RlOut(0, C); CrLf(0); F:= 1.8*C + 32.0; ChOut(0, ^F); RlOut(0, F); CrLf(0); R:= F + 459.67; ChOut(0, ^R); RlOut(0, R); CrLf(0); ]
http://rosettacode.org/wiki/Suffixation_of_decimal_numbers
Suffixation of decimal numbers
Suffixation:   a letter or a group of letters added to the end of a word to change its meaning.       ─────   or, as used herein   ───── Suffixation:   the addition of a metric or "binary" metric suffix to a number, with/without rounding. Task Write a function(s) to append (if possible)   a metric   or   a "binary" metric   suffix to a number   (displayed in decimal). The number may be rounded   (as per user specification)   (via shortening of the number when the number of digits past the decimal point are to be used). Task requirements   write a function (or functions) to add   (if possible)   a suffix to a number   the function(s) should be able to express the number (possibly with a suffix) in as many decimal digits as specified   the sign should be preserved   (if present)   the number may have commas within the number   (the commas need not be preserved)   the number may have a decimal point and/or an exponent as in:   -123.7e-01   the suffix that might be appended should be in uppercase;   however, the   i   should be in lowercase   support:   the            metric suffixes:   K  M  G  T  P  E  Z  Y  X  W  V  U   the binary metric suffixes:   Ki Mi Gi Ti Pi Ei Zi Yi Xi Wi Vi Ui   the (full name) suffix:   googol   (lowercase)   (equal to 1e100)     (optional)   a number of decimal digits past the decimal point   (with rounding).   The default is to display all significant digits   validation of the (supplied/specified) arguments is optional but recommended   display   (with identifying text):   the original number   (with identifying text)   the number of digits past the decimal point being used   (or none, if not specified)   the type of suffix being used   (metric or "binary" metric)   the (new) number with the appropriate   (if any)   suffix   all output here on this page Metric suffixes to be supported   (whether or not they're officially sanctioned) K multiply the number by 10^3 kilo (1,000) M multiply the number by 10^6 mega (1,000,000) G multiply the number by 10^9 giga (1,000,000,000) T multiply the number by 10^12 tera (1,000,000,000,000) P multiply the number by 10^15 peta (1,000,000,000,000,000) E multiply the number by 10^18 exa (1,000,000,000,000,000,000) Z multiply the number by 10^21 zetta (1,000,000,000,000,000,000,000) Y multiply the number by 10^24 yotta (1,000,000,000,000,000,000,000,000) X multiply the number by 10^27 xenta (1,000,000,000,000,000,000,000,000,000) W multiply the number by 10^30 wekta (1,000,000,000,000,000,000,000,000,000,000) V multiply the number by 10^33 vendeka (1,000,000,000,000,000,000,000,000,000,000,000) U multiply the number by 10^36 udekta (1,000,000,000,000,000,000,000,000,000,000,000,000) "Binary" suffixes to be supported   (whether or not they're officially sanctioned) Ki multiply the number by 2^10 kibi (1,024) Mi multiply the number by 2^20 mebi (1,048,576) Gi multiply the number by 2^30 gibi (1,073,741,824) Ti multiply the number by 2^40 tebi (1,099,571,627,776) Pi multiply the number by 2^50 pebi (1,125,899,906,884,629) Ei multiply the number by 2^60 exbi (1,152,921,504,606,846,976) Zi multiply the number by 2^70 zebi (1,180,591,620,717,411,303,424) Yi multiply the number by 2^80 yobi (1,208,925,819,614,629,174,706,176) Xi multiply the number by 2^90 xebi (1,237,940,039,285,380,274,899,124,224) Wi multiply the number by 2^100 webi (1,267,650,600,228,229,401,496,703,205,376) Vi multiply the number by 2^110 vebi (1,298,074,214,633,706,907,132,624,082,305,024) Ui multiply the number by 2^120 uebi (1,329,227,995,784,915,872,903,807,060,280,344,576) For instance, with this pseudo─code /* 1st arg: the number to be transformed.*/ /* 2nd arg: # digits past the dec. point.*/ /* 3rd arg: the type of suffix to use. */ /* 2 indicates "binary" suffix.*/ /* 10 indicates decimal suffix.*/ a = '456,789,100,000,000' /* "A" has eight trailing zeros. */ say ' aa=' suffize(a) /* Display a suffized number to terminal.*/ /* The "1" below shows one decimal ···*/ /* digit past the decimal point. */ n = suffize(a, 1) /* SUFFIZE is the function name. */ n = suffize(a, 1, 10) /* (identical to the above statement.) */ say ' n=' n /* Display value of N to terminal. */ /* Note the rounding that occurs. */ f = suffize(a, 1, 2) /* SUFFIZE with one fractional digit */ say ' f=' f /* Display value of F to terminal. */ /* Display value in "binary" metric. */ bin = suffize(a, 5, 2) /* SUFFIZE with binary metric suffix. */ say 'bin=' bin /* Display value of BIN to terminal. */ win = suffize(a, 0, 2) /* SUFFIZE with binary metric suffix. */ say 'win=' win /* Display value of WIN to terminal. */ xvi = ' +16777216 ' /* this used to be a big computer ··· */ big = suffize(xvi, , 2) /* SUFFIZE with binary metric suffix. */ say 'big=' big /* Display value of BIG to terminal. */ would display: aa= 456.7891T n= 456.8T f= 415.4Ti bin= 415.44727Ti win= 415Ti big= 16Mi Use these test cases 87,654,321 -998,877,665,544,332,211,000 3 +112,233 0 16,777,216 1 456,789,100,000,000 2 456,789,100,000,000 2 10 456,789,100,000,000 5 2 456,789,100,000.000e+00 0 10 +16777216 , 2 1.2e101 (your primary disk free space) 1 ◄■■■■■■■ optional Use whatever parameterizing your computer language supports,   and it's permitted to create as many separate functions as are needed   (if needed)   if   function arguments aren't allowed to be omitted or varied. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#REXX
REXX
/*REXX program to add a (either metric or "binary" metric) suffix to a decimal number.*/ @.= /*default value for the stemmed array. */ parse arg @.1 /*obtain optional arguments from the CL*/ if @.1=='' then do; @.1= ' 87,654,321 ' @.2= ' -998,877,665,544,332,211,000 3 ' @.3= ' +112,233 0 ' @.4= ' 16,777,216 1 '   @.5= ' 456,789,100,000,000 2 ' @.5= ' 456,789,100,000,000 '   @.6= ' 456,789,100,000,000 2 10 ' @.7= ' 456,789,100,000,000 5 2 ' @.8= ' 456,789,100,000.000e+00 0 10 ' @.9= ' +16777216 , 2 ' @.10= ' 1.2e101 ' @.11= ' 134,112,411,648 1 ' /*via DIR*/ end /*@.11≡ amount of free space on my C: */   do i=1 while @.i\==''; say copies("─", 60) /*display a separator betweenst values.*/ parse var @.i x f r . /*get optional arguments from the list.*/ say ' input number=' x /*show original number to the term.*/ say ' fraction digs=' f /* " specified fracDigs " " " */ say ' specified radix=' r /* " specified radix " " " */ say ' new number=' suffize(x, f, r) /*maybe append an "alphabetic" suffix. */ end /*i*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ suffize: procedure; arg s 2 1 n, f, b /*obtain: sign, N, fractionDigs, base.*/ if digits()<99 then numeric digits 500 /*use enough dec. digs for arithmetic. */ @err = '***error*** (from SUFFIZE) ' /*literal used when returning err msg. */ if b=='' then b= 10; o= b /*assume a base (ten) if omitted. */ n= space( translate(n,,','), 0); m= n /*elide commas from the 1st argument.*/ f= space( translate(f,,','), 0) /*elide commas from the 2nd argument.*/ if \datatype(n, 'N') then return @err "1st argument isn't numeric." if f=='' then f= length(space(translate(n,,.), 0)) /*F omitted? Use full len.*/ if \datatype(f, 'W') then return @err "2nd argument isn't an integer: " f if f<0 then return @err "2nd argument can't be negative. " f if \datatype(b, 'W') then return @err "3rd argument isn't an integer. " b if b\==10 & b\==2 then return @err "3rd argument isn't a 10 or 2." b if arg()>3 then return @err "too many arguments were specified." @= ' KMGTPEZYXWVU' /*metric uppercase suffixes, with blank*/  !.=;  !.2= 'i' /*set default suffix; "binary" suffix.*/ i= 3; b= abs(b); if b==2 then i= 10 /*a power of ten; or a power of 2**10 */ if \datatype(n, 'N') | pos('E', n/1)\==0 then return m /* ¬num or has an "E"*/ sig=; if s=='-' | s=="+" then sig=s /*preserve the number's sign if present*/ n= abs(n) /*possibly round number, & remove sign.*/   do while n>=1e100 & b==10; x=n/1e100 /*is N ≥ googol and base=10? A googol?*/ if pos(., x)\==0 & o<0 then leave /*does # have a dec. point or is B<0? */ return sig || x'googol' /*maybe prepend the sign, add GOOGOL. */ end /*while*/   do j=length(@)-1 to 1 by -1 while n>0 /*see if # is a multiple of 1024. */ $= b ** (i*j) /*compute base raised to a power. */ if n<$ then iterate /*N not big enough? Keep trying. */ n= format(n/$, , min( digits(), f) ) / 1 /*reformat number with a fraction. */ if pos(., n)\==0 & o<0 then return m /*has a decimal point or is B<0? */ leave /*leave this DO loop at this point.*/ end /*j*/   if n=0 then j=0 /*N = 0? Don't use any suffix. */ return sig||strip(n||substr(@, j+1,1))!.b /*add sign, suffixes, strip blanks.*/
http://rosettacode.org/wiki/Sum_of_a_series
Sum of a series
Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k = 1 n 1 k 2 {\displaystyle S_{n}=\sum _{k=1}^{n}{\frac {1}{k^{2}}}} and compute   S 1000 {\displaystyle S_{1000}} This approximates the   zeta function   for   S=2,   whose exact value ζ ( 2 ) = π 2 6 {\displaystyle \zeta (2)={\pi ^{2} \over 6}} is the solution of the Basel problem.
#ALGOL_W
ALGOL W
begin % compute the sum of 1/k^2 for k = 1..1000 % integer k;  % computes the sum of a series from lo to hi using Jensen's Device % real procedure sum ( integer %name% k; integer value lo, hi; real procedure term ); begin real temp; temp := 0; k := lo; while k <= hi do begin temp := temp + term; k := k + 1 end while_k_le_temp; temp end; write( r_format := "A", r_w := 8, r_d := 5, sum( k, 1, 1000, 1 / ( k * k ) ) ) end.
http://rosettacode.org/wiki/System_time
System time
Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related task   Date format See also   Retrieving system time (wiki)
#TI-89_BASIC
TI-89 BASIC
■ getTime() {13 28 55} ■ getDate() {2009 8 13}
http://rosettacode.org/wiki/System_time
System time
Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related task   Date format See also   Retrieving system time (wiki)
#True_BASIC
True BASIC
PRINT DATE$ ! returns SYSTEM date in format: “YYYYMMDD”. ! Here YYYY IS the year, MM IS the month number, AND DD IS the day number.   PRINT TIME$ ! returns SYSTEM time in format: “HH:MM:SS”. END
http://rosettacode.org/wiki/Sum_to_100
Sum to 100
Task Find solutions to the   sum to one hundred   puzzle. Add (insert) the mathematical operators     +   or   -     (plus or minus)   before any of the digits in the decimal numeric string   123456789   such that the resulting mathematical expression adds up to a particular sum   (in this iconic case,   100). Example: 123 + 4 - 5 + 67 - 89 = 100 Show all output here.   Show all solutions that sum to   100   Show the sum that has the maximum   number   of solutions   (from zero to infinity‡)   Show the lowest positive sum that   can't   be expressed   (has no solutions),   using the rules for this task   Show the ten highest numbers that can be expressed using the rules for this task   (extra credit) ‡   (where   infinity   would be a relatively small   123,456,789) An example of a sum that can't be expressed   (within the rules of this task)   is:   5074 (which,   of course,   isn't the lowest positive sum that can't be expressed).
#11l
11l
-V NUMBER_OF_DIGITS = 9 THREE_POW_4 = 3 * 3 * 3 * 3 NUMBER_OF_EXPRESSIONS = 2 * THREE_POW_4 * THREE_POW_4   T.enum Op ADD SUB JOIN   T Expression code = [Op.ADD] * :NUMBER_OF_DIGITS   F inc() L(i) 0 .< .code.len .code[i] = Op((Int(.code[i]) + 1) % 3) I .code[i] != ADD L.break   F toInt() V value = 0 V number = 0 V sign = 1 L(digit) 1..9 V c = .code[:NUMBER_OF_DIGITS - digit] I c == ADD {value += sign * number; number = digit; sign = 1} E I c == SUB {value += sign * number; number = digit; sign = -1} E {number = 10 * number + digit} R value + sign * number   F String() V s = ‘’ L(digit) 1 .. :NUMBER_OF_DIGITS V c = .code[:NUMBER_OF_DIGITS - digit] I c == ADD I digit > 1 s ‘’= ‘ + ’ E I c == SUB s ‘’= ‘ - ’ s ‘’= String(digit) R s.ltrim(‘ ’)   F printe(givenSum) V expression = Expression() L 0 .< :NUMBER_OF_EXPRESSIONS I expression.toInt() == givenSum print(‘#9’.format(givenSum)‘ = ’expression) expression.inc()   T Stat DefaultDict[Int, Int] countSum DefaultDict[Int, Set[Int]] sumCount F () V expression = Expression() L 0 .< :NUMBER_OF_EXPRESSIONS V sum = expression.toInt() .countSum[sum]++ expression.inc() L(k, v) .countSum .sumCount[v].add(k)   print("100 has the following solutions:\n") printe(100)   V stat = Stat() V maxCount = max(stat.sumCount.keys()) V maxSum = max(stat.sumCount[maxCount]) print("\n#. has the maximum number of solutions, namely #.".format(maxSum, maxCount))   V value = 0 L value C stat.countSum value++ print("\n#. is the lowest positive number with no solutions".format(value))   print("\nThe ten highest numbers that do have solutions are:\n") L(i) sorted(stat.countSum.keys(), reverse' 1B)[0.<10] printe(i)
http://rosettacode.org/wiki/Sum_multiples_of_3_and_5
Sum multiples of 3 and 5
Task The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n. Show output for n = 1000. This is is the same as Project Euler problem 1. Extra credit: do this efficiently for n = 1e20 or higher.
#AppleScript
AppleScript
----------------- SUM MULTIPLES OF 3 AND 5 -----------------   -- sum35 :: Int -> Int on sum35(n) tell sumMults(n) |λ|(3) + |λ|(5) - |λ|(15) end tell end sum35       -- sumMults :: Int -> Int -> Int on sumMults(n) -- Area under straight line -- between first multiple and last. script on |λ|(m) set n1 to (n - 1) div m m * n1 * (n1 + 1) div 2 end |λ| end script end sumMults     --------------------------- TEST --------------------------- on run -- sum35Result :: String -> Int -> Int -> String script sum35Result -- sums of all multiples of 3 or 5 below or equal to N -- for N = 10 to N = 10E8 (limit of AS integers) on |λ|(a, x, i) a & "10<sup>" & i & "</sup> -> " & ¬ sum35(10 ^ x) & "<br>" end |λ| end script foldl(sum35Result, "", enumFromTo(1, 8)) end run     -------------------- GENERIC FUNCTIONS ---------------------   -- enumFromTo :: Int -> Int -> [Int] on enumFromTo(m, n) if m > n then set d to -1 else set d to 1 end if set lst to {} repeat with i from m to n by d set end of lst to i end repeat return lst end enumFromTo   -- foldl :: (a -> b -> a) -> a -> [b] -> a on foldl(f, startValue, xs) tell mReturn(f) set v to startValue set lng to length of xs repeat with i from 1 to lng set v to |λ|(v, item i of xs, i, xs) end repeat return v end tell end foldl   -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: Handler -> Script on mReturn(f) if class of f is script then f else script property |λ| : f end script end if end mReturn
http://rosettacode.org/wiki/Sum_digits_of_an_integer
Sum digits of an integer
Task Take a   Natural Number   in a given base and return the sum of its digits:   110         sums to   1   123410   sums to   10   fe16       sums to   29   f0e16     sums to   29
#ArnoldC
ArnoldC
LISTEN TO ME VERY CAREFULLY sumDigits I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE n I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE base GIVE THESE PEOPLE AIR HEY CHRISTMAS TREE sum YOU SET US UP @I LIED STICK AROUND n HEY CHRISTMAS TREE digit YOU SET US UP @I LIED GET TO THE CHOPPER digit HERE IS MY INVITATION n I LET HIM GO base ENOUGH TALK GET TO THE CHOPPER sum HERE IS MY INVITATION sum GET UP digit ENOUGH TALK GET TO THE CHOPPER n HERE IS MY INVITATION n HE HAD TO SPLIT base ENOUGH TALK CHILL I'LL BE BACK sum HASTA LA VISTA, BABY   IT'S SHOWTIME HEY CHRISTMAS TREE sum YOU SET US UP @I LIED GET YOUR A** TO MARS sum DO IT NOW sumDigits 12345 10 TALK TO THE HAND "sumDigits 12345 10 =" TALK TO THE HAND sum GET YOUR A** TO MARS sum DO IT NOW sumDigits 254 16 TALK TO THE HAND "sumDigits 254 16 =" TALK TO THE HAND sum YOU HAVE BEEN TERMINATED
http://rosettacode.org/wiki/Sum_of_squares
Sum of squares
Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
#ALGOL_W
ALGOL W
begin  % procedure to sum the elements of a vector. As the procedure can't find %  % the bounds of the array for itself, we pass them in lb and ub  % real procedure sumSquares ( real array vector ( * )  ; integer value lb  ; integer value ub ) ; begin real sum; sum := 0; for i := lb until ub do sum := sum + ( vector( i ) * vector( i ) ); sum end sumOfSquares ;    % test the sumSquares procedure  % real array numbers ( 1 :: 5 ); for i := 1 until 5 do numbers( i ) := i; r_format := "A"; r_w := 10; r_d := 1; % set fixed point output  % write( sumSquares( numbers, 1, 5 ) ); end.
http://rosettacode.org/wiki/Sum_of_squares
Sum of squares
Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
#Alore
Alore
def sum_squares(a) var sum = 0 for i in a sum = sum + i**2 end return sum end   WriteLn(sum_squares([3,1,4,1,5,9])) end
http://rosettacode.org/wiki/Sum_and_product_of_an_array
Sum and product of an array
Task Compute the sum and product of an array of integers.
#Action.21
Action!
DEFINE LAST="6"   PROC Main() INT ARRAY data=[1 2 3 4 5 6 7] BYTE i INT a,res   res=0 FOR i=0 TO LAST DO a=data(i) PrintI(a) IF i=LAST THEN Put('=) ELSE Put('+) FI res==+a OD PrintIE(res)   res=1 FOR i=0 TO LAST DO a=data(i) PrintI(a) IF i=LAST THEN Put('=) ELSE Put('*) FI res=res*a OD PrintIE(res) RETURN
http://rosettacode.org/wiki/Sum_and_product_puzzle
Sum and product puzzle
Task[edit] Solve the "Impossible Puzzle": X and Y are two different whole numbers greater than 1. Their sum is no greater than 100, and Y is greater than X. S and P are two mathematicians (and consequently perfect logicians); S knows the sum X+Y and P knows the product X*Y. Both S and P know all the information in this paragraph. The following conversation occurs: S says "P does not know X and Y." P says "Now I know X and Y." S says "Now I also know X and Y!" What are X and Y? Guidance It can be hard to wrap one's head around what the three lines of dialog between S (the "sum guy") and P (the "product guy") convey about the values of X and Y. So for your convenience, here's a break-down: Quote Implied fact 1) S says "P does not know X and Y." For every possible sum decomposition of the number X+Y, the product has in turn more than one product decomposition. 2) P says "Now I know X and Y." The number X*Y has only one product decomposition for which fact 1 is true. 3) S says "Now I also know X and Y." The number X+Y has only one sum decomposition for which fact 2 is true. Terminology: "sum decomposition" of a number = Any pair of positive integers (A, B) so that A+B equals the number. Here, with the additional constraint 2 ≤ A < B. "product decomposition" of a number = Any pair of positive integers (A, B) so that A*B equals the number. Here, with the additional constraint 2 ≤ A < B. Your program can solve the puzzle by considering all possible pairs (X, Y) in the range 2 ≤ X < Y ≤ 98, and then successively eliminating candidates based on the three facts. It turns out only one solution remains! See the Python example for an implementation that uses this approach with a few optimizations. See also   Wikipedia:   Sum and Product Puzzle
#Racket
Racket
#lang racket (define-syntax-rule (define/mem (name args ...) body ...) (begin (define cache (make-hash)) (define (name args ...) (hash-ref! cache (list args ...) (lambda () body ...)))))   (define (sum p) (+ (first p) (second p))) (define (mul p) (* (first p) (second p)))   (define (sum= p s) (filter (lambda (q) (= p (sum q))) s)) (define (mul= p s) (filter (lambda (q) (= p (mul q))) s))   (define (puzzle tot) (printf "Max Sum: ~a\n" tot) (define s1 (for*/list ([x (in-range 2 (add1 tot))] [y (in-range (add1 x) (- (add1 tot) x))]) (list x y))) (printf "Possible pairs: ~a\n" (length s1))   (define/mem (sumEq/all p) (sum= p s1)) (define/mem (mulEq/all p) (mul= p s1))   (define s2 (filter (lambda (p) (andmap (lambda (q) (not (= (length (mulEq/all (mul q))) 1))) (sumEq/all (sum p)))) s1)) (printf "Initial pairs for S: ~a\n" (length s2))   (define s3 (filter (lambda (p) (= (length (mul= (mul p) s2)) 1)) s2)) (displayln (length s3)) (printf "Pairs for P: ~a\n" (length s3))   (define s4 (filter (lambda (p) (= (length (sum= (sum p) s3)) 1)) s3)) (printf "Final pairs for S: ~a\n" (length s4))   (displayln s4))   (puzzle 100)
http://rosettacode.org/wiki/Temperature_conversion
Temperature conversion
There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones: Kelvin, Celsius, Fahrenheit, and Rankine. The Celsius and Kelvin scales have the same magnitude, but different null points. 0 degrees Celsius corresponds to 273.15 kelvin. 0 kelvin is absolute zero. The Fahrenheit and Rankine scales also have the same magnitude, but different null points. 0 degrees Fahrenheit corresponds to 459.67 degrees Rankine. 0 degrees Rankine is absolute zero. The Celsius/Kelvin and Fahrenheit/Rankine scales have a ratio of 5 : 9. Task Write code that accepts a value of kelvin, converts it to values of the three other scales, and prints the result. Example K 21.00 C -252.15 F -421.87 R 37.80
#zkl
zkl
K:=ask(0,"Kelvin: ").toFloat(); println("K %.2f".fmt(K)); println("F %.2f".fmt(K*1.8 - 459.67)); println("C %.2f".fmt(K - 273.15)); println("R %.2f".fmt(K*1.8));
http://rosettacode.org/wiki/Temperature_conversion
Temperature conversion
There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones: Kelvin, Celsius, Fahrenheit, and Rankine. The Celsius and Kelvin scales have the same magnitude, but different null points. 0 degrees Celsius corresponds to 273.15 kelvin. 0 kelvin is absolute zero. The Fahrenheit and Rankine scales also have the same magnitude, but different null points. 0 degrees Fahrenheit corresponds to 459.67 degrees Rankine. 0 degrees Rankine is absolute zero. The Celsius/Kelvin and Fahrenheit/Rankine scales have a ratio of 5 : 9. Task Write code that accepts a value of kelvin, converts it to values of the three other scales, and prints the result. Example K 21.00 C -252.15 F -421.87 R 37.80
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 REM Translation of traditional basic version 20 INPUT "Kelvin Degrees? ";k 30 IF k <= 0 THEN STOP: REM A value of zero or less will end program 40 LET c = k - 273.15 50 LET f = k * 1.8 - 459.67 60 LET r = k * 1.8 70 PRINT k; " Kelvin is equivalent to" 80 PRINT c; " Degrees Celsius" 90 PRINT f; " Degrees Fahrenheit" 100 PRINT r; " Degrees Rankine" 110 GO TO 20
http://rosettacode.org/wiki/Suffixation_of_decimal_numbers
Suffixation of decimal numbers
Suffixation:   a letter or a group of letters added to the end of a word to change its meaning.       ─────   or, as used herein   ───── Suffixation:   the addition of a metric or "binary" metric suffix to a number, with/without rounding. Task Write a function(s) to append (if possible)   a metric   or   a "binary" metric   suffix to a number   (displayed in decimal). The number may be rounded   (as per user specification)   (via shortening of the number when the number of digits past the decimal point are to be used). Task requirements   write a function (or functions) to add   (if possible)   a suffix to a number   the function(s) should be able to express the number (possibly with a suffix) in as many decimal digits as specified   the sign should be preserved   (if present)   the number may have commas within the number   (the commas need not be preserved)   the number may have a decimal point and/or an exponent as in:   -123.7e-01   the suffix that might be appended should be in uppercase;   however, the   i   should be in lowercase   support:   the            metric suffixes:   K  M  G  T  P  E  Z  Y  X  W  V  U   the binary metric suffixes:   Ki Mi Gi Ti Pi Ei Zi Yi Xi Wi Vi Ui   the (full name) suffix:   googol   (lowercase)   (equal to 1e100)     (optional)   a number of decimal digits past the decimal point   (with rounding).   The default is to display all significant digits   validation of the (supplied/specified) arguments is optional but recommended   display   (with identifying text):   the original number   (with identifying text)   the number of digits past the decimal point being used   (or none, if not specified)   the type of suffix being used   (metric or "binary" metric)   the (new) number with the appropriate   (if any)   suffix   all output here on this page Metric suffixes to be supported   (whether or not they're officially sanctioned) K multiply the number by 10^3 kilo (1,000) M multiply the number by 10^6 mega (1,000,000) G multiply the number by 10^9 giga (1,000,000,000) T multiply the number by 10^12 tera (1,000,000,000,000) P multiply the number by 10^15 peta (1,000,000,000,000,000) E multiply the number by 10^18 exa (1,000,000,000,000,000,000) Z multiply the number by 10^21 zetta (1,000,000,000,000,000,000,000) Y multiply the number by 10^24 yotta (1,000,000,000,000,000,000,000,000) X multiply the number by 10^27 xenta (1,000,000,000,000,000,000,000,000,000) W multiply the number by 10^30 wekta (1,000,000,000,000,000,000,000,000,000,000) V multiply the number by 10^33 vendeka (1,000,000,000,000,000,000,000,000,000,000,000) U multiply the number by 10^36 udekta (1,000,000,000,000,000,000,000,000,000,000,000,000) "Binary" suffixes to be supported   (whether or not they're officially sanctioned) Ki multiply the number by 2^10 kibi (1,024) Mi multiply the number by 2^20 mebi (1,048,576) Gi multiply the number by 2^30 gibi (1,073,741,824) Ti multiply the number by 2^40 tebi (1,099,571,627,776) Pi multiply the number by 2^50 pebi (1,125,899,906,884,629) Ei multiply the number by 2^60 exbi (1,152,921,504,606,846,976) Zi multiply the number by 2^70 zebi (1,180,591,620,717,411,303,424) Yi multiply the number by 2^80 yobi (1,208,925,819,614,629,174,706,176) Xi multiply the number by 2^90 xebi (1,237,940,039,285,380,274,899,124,224) Wi multiply the number by 2^100 webi (1,267,650,600,228,229,401,496,703,205,376) Vi multiply the number by 2^110 vebi (1,298,074,214,633,706,907,132,624,082,305,024) Ui multiply the number by 2^120 uebi (1,329,227,995,784,915,872,903,807,060,280,344,576) For instance, with this pseudo─code /* 1st arg: the number to be transformed.*/ /* 2nd arg: # digits past the dec. point.*/ /* 3rd arg: the type of suffix to use. */ /* 2 indicates "binary" suffix.*/ /* 10 indicates decimal suffix.*/ a = '456,789,100,000,000' /* "A" has eight trailing zeros. */ say ' aa=' suffize(a) /* Display a suffized number to terminal.*/ /* The "1" below shows one decimal ···*/ /* digit past the decimal point. */ n = suffize(a, 1) /* SUFFIZE is the function name. */ n = suffize(a, 1, 10) /* (identical to the above statement.) */ say ' n=' n /* Display value of N to terminal. */ /* Note the rounding that occurs. */ f = suffize(a, 1, 2) /* SUFFIZE with one fractional digit */ say ' f=' f /* Display value of F to terminal. */ /* Display value in "binary" metric. */ bin = suffize(a, 5, 2) /* SUFFIZE with binary metric suffix. */ say 'bin=' bin /* Display value of BIN to terminal. */ win = suffize(a, 0, 2) /* SUFFIZE with binary metric suffix. */ say 'win=' win /* Display value of WIN to terminal. */ xvi = ' +16777216 ' /* this used to be a big computer ··· */ big = suffize(xvi, , 2) /* SUFFIZE with binary metric suffix. */ say 'big=' big /* Display value of BIG to terminal. */ would display: aa= 456.7891T n= 456.8T f= 415.4Ti bin= 415.44727Ti win= 415Ti big= 16Mi Use these test cases 87,654,321 -998,877,665,544,332,211,000 3 +112,233 0 16,777,216 1 456,789,100,000,000 2 456,789,100,000,000 2 10 456,789,100,000,000 5 2 456,789,100,000.000e+00 0 10 +16777216 , 2 1.2e101 (your primary disk free space) 1 ◄■■■■■■■ optional Use whatever parameterizing your computer language supports,   and it's permitted to create as many separate functions as are needed   (if needed)   if   function arguments aren't allowed to be omitted or varied. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#VBA
VBA
Private Function suffize(number As String, Optional sfractiondigits As String, Optional base As String) As String Dim suffix As String, parts() As String, exponent As String Dim fractiondigits As Integer, nsuffix As Integer, flag As Boolean flag = False fractiondigits = Val(sfractiondigits) suffixes = " KMGTPEZYXWVU" number = Replace(number, ",", "", 1) Dim c As Currency Dim sign As Integer 'separate leading sign If Left(number, 1) = "-" Then number = Right(number, Len(number) - 1) outstring = "-" End If If Left(number, 1) = "+" Then number = Right(number, Len(number) - 1) outstring = "+" End If 'split exponent parts = Split(number, "e") number = parts(0) If UBound(parts) > 0 Then exponent = parts(1) 'split fraction parts = Split(number, ".") number = parts(0) If UBound(parts) > 0 Then frac = parts(1) If base = "2" Then Dim cnumber As Currency cnumber = Val(number) nsuffix = 0 Dim dnumber As Double If cnumber > 1023 Then cnumber = cnumber / 1024@ nsuffix = nsuffix + 1 dnumber = cnumber Do While dnumber > 1023 dnumber = dnumber / 1024@ 'caveat: currency has only 4 fractional digits ... nsuffix = nsuffix + 1 Loop number = CStr(dnumber) Else number = CStr(cnumber) End If leadingstring = Int(number) number = Replace(number, ",", "")   leading = Len(leadingstring) suffix = Mid(suffixes, nsuffix + 1, 1) Else 'which suffix nsuffix = (Len(number) + Val(exponent) - 1) \ 3 If nsuffix < 13 Then suffix = Mid(suffixes, nsuffix + 1, 1) leading = (Len(number) - 1) Mod 3 + 1 leadingstring = Left(number, leading) Else flag = True If nsuffix > 32 Then suffix = "googol" leading = Len(number) + Val(exponent) - 99 leadingstring = number & frac & String$(Val(exponent) - 100 - Len(frac), "0") Else suffix = "U" leading = Len(number) + Val(exponent) - 35 If Val(exponent) > 36 Then leadingstring = number & String$(Val(exponent) - 36, "0") Else leadingstring = Left(number, (Len(number) - 36 + Val(exponent))) End If End If End If End If 'round up if necessary If fractiondigits > 0 Then If Val(Mid(number, leading + fractiondigits + 1, 1)) >= 5 Then fraction = Mid(number, leading + 1, fractiondigits - 1) & _ CStr(Val(Mid(number, leading + fractiondigits, 1)) + 1) Else fraction = Mid(number, leading + 1, fractiondigits) End If Else If Val(Mid(number, leading + 1, 1)) >= 5 And sfractiondigits <> "" And sfractiondigits <> "," Then leadingstring = Mid(number, 1, leading - 1) & _ CStr(Val(Mid(number, leading, 1)) + 1) End If End If If flag Then If sfractiondigits = "" Or sfractiondigits = "," Then fraction = "" End If Else If sfractiondigits = "" Or sfractiondigits = "," Then fraction = Right(number, Len(number) - leading) End If End If outstring = outstring & leadingstring If Len(fraction) > 0 Then outstring = outstring & "." & fraction End If If base = "2" Then outstring = outstring & suffix & "i" Else outstring = outstring & suffix End If suffize = outstring End Function Sub program() Dim s(10) As String, t As String, f As String, r As String Dim tt() As String, temp As String s(0) = " 87,654,321" s(1) = " -998,877,665,544,332,211,000 3" s(2) = " +112,233 0" s(3) = " 16,777,216 1" s(4) = " 456,789,100,000,000 2" s(5) = " 456,789,100,000,000 2 10" s(6) = " 456,789,100,000,000 5 2" s(7) = " 456,789,100,000.000e+00 0 10" s(8) = " +16777216 , 2" s(9) = " 1.2e101" For i = 0 To 9 ReDim tt(0) t = Trim(s(i)) Do temp = t t = Replace(t, " ", " ") Loop Until temp = t tt = Split(t, " ") If UBound(tt) > 0 Then f = tt(1) Else f = "" If UBound(tt) > 1 Then r = tt(2) Else r = "" Debug.Print String$(48, "-") Debug.Print " input number = "; tt(0) Debug.Print " fraction digs = "; f Debug.Print " specified radix = "; r Debug.Print " new number = "; suffize(tt(0), f, r) Next i End Sub
http://rosettacode.org/wiki/Sum_of_a_series
Sum of a series
Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k = 1 n 1 k 2 {\displaystyle S_{n}=\sum _{k=1}^{n}{\frac {1}{k^{2}}}} and compute   S 1000 {\displaystyle S_{1000}} This approximates the   zeta function   for   S=2,   whose exact value ζ ( 2 ) = π 2 6 {\displaystyle \zeta (2)={\pi ^{2} \over 6}} is the solution of the Basel problem.
#APL
APL
+/÷2*⍨⍳1000 1.64393
http://rosettacode.org/wiki/System_time
System time
Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related task   Date format See also   Retrieving system time (wiki)
#TUSCRIPT
TUSCRIPT
  $$ MODE TUSCRIPT time=time() PRINT time
http://rosettacode.org/wiki/System_time
System time
Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related task   Date format See also   Retrieving system time (wiki)
#UNIX_Shell
UNIX Shell
date # Thu Dec 3 15:38:06 PST 2009   date +%s # 1259883518, seconds since the epoch, like C stdlib time(0)
http://rosettacode.org/wiki/Sum_to_100
Sum to 100
Task Find solutions to the   sum to one hundred   puzzle. Add (insert) the mathematical operators     +   or   -     (plus or minus)   before any of the digits in the decimal numeric string   123456789   such that the resulting mathematical expression adds up to a particular sum   (in this iconic case,   100). Example: 123 + 4 - 5 + 67 - 89 = 100 Show all output here.   Show all solutions that sum to   100   Show the sum that has the maximum   number   of solutions   (from zero to infinity‡)   Show the lowest positive sum that   can't   be expressed   (has no solutions),   using the rules for this task   Show the ten highest numbers that can be expressed using the rules for this task   (extra credit) ‡   (where   infinity   would be a relatively small   123,456,789) An example of a sum that can't be expressed   (within the rules of this task)   is:   5074 (which,   of course,   isn't the lowest positive sum that can't be expressed).
#Ada
Ada
package Sum_To is   generic with procedure Callback(Str: String; Int: Integer); procedure Eval;   generic Number: Integer; with function Print_If(Sum, Number: Integer) return Boolean; procedure Print(S: String; Sum: Integer);   end Sum_To;
http://rosettacode.org/wiki/Sum_multiples_of_3_and_5
Sum multiples of 3 and 5
Task The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n. Show output for n = 1000. This is is the same as Project Euler problem 1. Extra credit: do this efficiently for n = 1e20 or higher.
#Arturo
Arturo
sumMul35: function [n][ sum select 1..n-1 [x][or? 0=x%3 0=x%5] ]   print sumMul35 1000
http://rosettacode.org/wiki/Sum_digits_of_an_integer
Sum digits of an integer
Task Take a   Natural Number   in a given base and return the sum of its digits:   110         sums to   1   123410   sums to   10   fe16       sums to   29   f0e16     sums to   29
#Arturo
Arturo
sumDigits: function [n base][ result: 0 while [n>0][ result: result + n%base n: n/base ] return result ]   print sumDigits 1 10 print sumDigits 12345 10 print sumDigits 123045 10 print sumDigits from.hex "0xfe" 16 print sumDigits from.hex "0xf0e" 16
http://rosettacode.org/wiki/Sum_of_squares
Sum of squares
Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
#APL
APL
square_sum←{+/⍵*2} square_sum 1 2 3 4 5 55 square_sum ⍬ ⍝The empty vector 0
http://rosettacode.org/wiki/Sum_of_squares
Sum of squares
Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
#AppleScript
AppleScript
------ TWO APPROACHES – SUM OVER MAP, AND DIRECT FOLD ----   -- sumOfSquares :: Num a => [a] -> a on sumOfSquares(xs) script squared on |λ|(x) x ^ 2 end |λ| end script   sum(map(squared, xs)) end sumOfSquares     -- sumOfSquares2 :: Num a => [a] -> a on sumOfSquares2(xs) script plusSquare on |λ|(a, x) a + x ^ 2 end |λ| end script   foldl(plusSquare, 0, xs) end sumOfSquares2     --------------------------- TEST ------------------------- on run set xs to [3, 1, 4, 1, 5, 9]   {sumOfSquares(xs), sumOfSquares2(xs)}   -- {133.0, 133.0} end run     -------------------- GENERIC FUNCTIONS -------------------   -- foldl :: (a -> b -> a) -> a -> [b] -> a on foldl(f, startValue, xs) tell mReturn(f) set v to startValue set lng to length of xs repeat with i from 1 to lng set v to |λ|(v, item i of xs, i, xs) end repeat return v end tell end foldl     -- map :: (a -> b) -> [a] -> [b] on map(f, xs) tell mReturn(f) set lng to length of xs set lst to {} repeat with i from 1 to lng set end of lst to |λ|(item i of xs, i, xs) end repeat return lst end tell end map     -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: Handler -> Script on mReturn(f) if class of f is script then f else script property |λ| : f end script end if end mReturn     -- sum :: Num a => [a] -> a on sum(xs) script add on |λ|(a, b) a + b end |λ| end script   foldl(add, 0, xs) end sum
http://rosettacode.org/wiki/Sum_and_product_of_an_array
Sum and product of an array
Task Compute the sum and product of an array of integers.
#ActionScript
ActionScript
package { import flash.display.Sprite;   public class SumAndProduct extends Sprite { public function SumAndProduct() { var arr:Array = [1, 2, 3, 4, 5]; var sum:int = 0; var prod:int = 1;   for (var i:int = 0; i < arr.length; i++) { sum += arr[i]; prod *= arr[i]; }   trace("Sum: " + sum); // 15 trace("Product: " + prod); // 120 } } }
http://rosettacode.org/wiki/Sum_and_product_puzzle
Sum and product puzzle
Task[edit] Solve the "Impossible Puzzle": X and Y are two different whole numbers greater than 1. Their sum is no greater than 100, and Y is greater than X. S and P are two mathematicians (and consequently perfect logicians); S knows the sum X+Y and P knows the product X*Y. Both S and P know all the information in this paragraph. The following conversation occurs: S says "P does not know X and Y." P says "Now I know X and Y." S says "Now I also know X and Y!" What are X and Y? Guidance It can be hard to wrap one's head around what the three lines of dialog between S (the "sum guy") and P (the "product guy") convey about the values of X and Y. So for your convenience, here's a break-down: Quote Implied fact 1) S says "P does not know X and Y." For every possible sum decomposition of the number X+Y, the product has in turn more than one product decomposition. 2) P says "Now I know X and Y." The number X*Y has only one product decomposition for which fact 1 is true. 3) S says "Now I also know X and Y." The number X+Y has only one sum decomposition for which fact 2 is true. Terminology: "sum decomposition" of a number = Any pair of positive integers (A, B) so that A+B equals the number. Here, with the additional constraint 2 ≤ A < B. "product decomposition" of a number = Any pair of positive integers (A, B) so that A*B equals the number. Here, with the additional constraint 2 ≤ A < B. Your program can solve the puzzle by considering all possible pairs (X, Y) in the range 2 ≤ X < Y ≤ 98, and then successively eliminating candidates based on the three facts. It turns out only one solution remains! See the Python example for an implementation that uses this approach with a few optimizations. See also   Wikipedia:   Sum and Product Puzzle
#Raku
Raku
sub grep-unique (&by, @list) { @list.classify(&by).values.grep(* == 1).map(*[0]) } sub sums ($n) { ($_, $n - $_ for 2 .. $n div 2) } sub sum ([$x, $y]) { $x + $y } sub product ([$x, $y]) { $x * $y }   my @all-pairs = (|($_ X $_+1 .. 98) for 2..97);   # Fact 1: my %p-unique := Set.new: map ~*, grep-unique &product, @all-pairs; my @s-pairs = @all-pairs.grep: { none (%p-unique{~$_} for sums sum $_) };   # Fact 2: my @p-pairs = grep-unique &product, @s-pairs;   # Fact 3: my @final-pairs = grep-unique &sum, @p-pairs;   printf "X = %d, Y = %d\n", |$_ for @final-pairs;
http://rosettacode.org/wiki/Suffixation_of_decimal_numbers
Suffixation of decimal numbers
Suffixation:   a letter or a group of letters added to the end of a word to change its meaning.       ─────   or, as used herein   ───── Suffixation:   the addition of a metric or "binary" metric suffix to a number, with/without rounding. Task Write a function(s) to append (if possible)   a metric   or   a "binary" metric   suffix to a number   (displayed in decimal). The number may be rounded   (as per user specification)   (via shortening of the number when the number of digits past the decimal point are to be used). Task requirements   write a function (or functions) to add   (if possible)   a suffix to a number   the function(s) should be able to express the number (possibly with a suffix) in as many decimal digits as specified   the sign should be preserved   (if present)   the number may have commas within the number   (the commas need not be preserved)   the number may have a decimal point and/or an exponent as in:   -123.7e-01   the suffix that might be appended should be in uppercase;   however, the   i   should be in lowercase   support:   the            metric suffixes:   K  M  G  T  P  E  Z  Y  X  W  V  U   the binary metric suffixes:   Ki Mi Gi Ti Pi Ei Zi Yi Xi Wi Vi Ui   the (full name) suffix:   googol   (lowercase)   (equal to 1e100)     (optional)   a number of decimal digits past the decimal point   (with rounding).   The default is to display all significant digits   validation of the (supplied/specified) arguments is optional but recommended   display   (with identifying text):   the original number   (with identifying text)   the number of digits past the decimal point being used   (or none, if not specified)   the type of suffix being used   (metric or "binary" metric)   the (new) number with the appropriate   (if any)   suffix   all output here on this page Metric suffixes to be supported   (whether or not they're officially sanctioned) K multiply the number by 10^3 kilo (1,000) M multiply the number by 10^6 mega (1,000,000) G multiply the number by 10^9 giga (1,000,000,000) T multiply the number by 10^12 tera (1,000,000,000,000) P multiply the number by 10^15 peta (1,000,000,000,000,000) E multiply the number by 10^18 exa (1,000,000,000,000,000,000) Z multiply the number by 10^21 zetta (1,000,000,000,000,000,000,000) Y multiply the number by 10^24 yotta (1,000,000,000,000,000,000,000,000) X multiply the number by 10^27 xenta (1,000,000,000,000,000,000,000,000,000) W multiply the number by 10^30 wekta (1,000,000,000,000,000,000,000,000,000,000) V multiply the number by 10^33 vendeka (1,000,000,000,000,000,000,000,000,000,000,000) U multiply the number by 10^36 udekta (1,000,000,000,000,000,000,000,000,000,000,000,000) "Binary" suffixes to be supported   (whether or not they're officially sanctioned) Ki multiply the number by 2^10 kibi (1,024) Mi multiply the number by 2^20 mebi (1,048,576) Gi multiply the number by 2^30 gibi (1,073,741,824) Ti multiply the number by 2^40 tebi (1,099,571,627,776) Pi multiply the number by 2^50 pebi (1,125,899,906,884,629) Ei multiply the number by 2^60 exbi (1,152,921,504,606,846,976) Zi multiply the number by 2^70 zebi (1,180,591,620,717,411,303,424) Yi multiply the number by 2^80 yobi (1,208,925,819,614,629,174,706,176) Xi multiply the number by 2^90 xebi (1,237,940,039,285,380,274,899,124,224) Wi multiply the number by 2^100 webi (1,267,650,600,228,229,401,496,703,205,376) Vi multiply the number by 2^110 vebi (1,298,074,214,633,706,907,132,624,082,305,024) Ui multiply the number by 2^120 uebi (1,329,227,995,784,915,872,903,807,060,280,344,576) For instance, with this pseudo─code /* 1st arg: the number to be transformed.*/ /* 2nd arg: # digits past the dec. point.*/ /* 3rd arg: the type of suffix to use. */ /* 2 indicates "binary" suffix.*/ /* 10 indicates decimal suffix.*/ a = '456,789,100,000,000' /* "A" has eight trailing zeros. */ say ' aa=' suffize(a) /* Display a suffized number to terminal.*/ /* The "1" below shows one decimal ···*/ /* digit past the decimal point. */ n = suffize(a, 1) /* SUFFIZE is the function name. */ n = suffize(a, 1, 10) /* (identical to the above statement.) */ say ' n=' n /* Display value of N to terminal. */ /* Note the rounding that occurs. */ f = suffize(a, 1, 2) /* SUFFIZE with one fractional digit */ say ' f=' f /* Display value of F to terminal. */ /* Display value in "binary" metric. */ bin = suffize(a, 5, 2) /* SUFFIZE with binary metric suffix. */ say 'bin=' bin /* Display value of BIN to terminal. */ win = suffize(a, 0, 2) /* SUFFIZE with binary metric suffix. */ say 'win=' win /* Display value of WIN to terminal. */ xvi = ' +16777216 ' /* this used to be a big computer ··· */ big = suffize(xvi, , 2) /* SUFFIZE with binary metric suffix. */ say 'big=' big /* Display value of BIG to terminal. */ would display: aa= 456.7891T n= 456.8T f= 415.4Ti bin= 415.44727Ti win= 415Ti big= 16Mi Use these test cases 87,654,321 -998,877,665,544,332,211,000 3 +112,233 0 16,777,216 1 456,789,100,000,000 2 456,789,100,000,000 2 10 456,789,100,000,000 5 2 456,789,100,000.000e+00 0 10 +16777216 , 2 1.2e101 (your primary disk free space) 1 ◄■■■■■■■ optional Use whatever parameterizing your computer language supports,   and it's permitted to create as many separate functions as are needed   (if needed)   if   function arguments aren't allowed to be omitted or varied. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Wren
Wren
import "/big" for BigRat import "/fmt" for Fmt   var suffixes = " KMGTPEZYXWVU" var googol = BigRat.fromDecimal("1e100")   var suffize = Fn.new { |arg| var fields = arg.split(" ").where { |s| s != "" }.toList if (fields.isEmpty) fields.add("0") var a = fields[0] var places var base var frac = "" var radix = "" var fc = fields.count if (fc == 1) { places = -1 base = 10 } else if (fc == 2) { places = Num.fromString(fields[1]) base = 10 frac = places.toString } else if (fc == 3) { if (fields[1] == ",") { places = 0 frac = "," } else { places = Num.fromString(fields[1]) frac = places.toString } base = Num.fromString(fields[2]) if (base !=2 && base != 10) base = 10 radix = base.toString } a = a.replace(",", "") // get rid of any commas var sign = "" if (a[0] == "+" || a[0] == "-") { sign = a[0] a = a[1..-1] // remove any sign after storing it } var b = BigRat.fromDecimal(a) var g = b >= googol var d = (!g && base == 2) ? BigRat.new(1024, 1) : (!g && base == 10) ? BigRat.new(1000, 1) : googol.copy() var c = 0 while (b >= d && c < 12) { // allow b >= 1K if c would otherwise exceed 12 b = b / d c = c + 1 } var suffix = !g ? suffixes[c] : "googol" if (base == 2) suffix = suffix + "i" System.print(" input number = %(fields[0])") System.print(" fraction digs = %(frac)") System.print("specified radix = %(radix)") System.write(" new number = ") BigRat.showAsInt = true if (places >= 0) { Fmt.print("$0s$s$s", sign, b.toDecimal(places), suffix) } else { Fmt.print("$0s$s$s", sign, b.toDecimal, suffix) } System.print() }   var tests = [ "87,654,321", "-998,877,665,544,332,211,000 3", "+112,233 0", "16,777,216 1", "456,789,100,000,000", "456,789,100,000,000 2 10", "456,789,100,000,000 5 2", "456,789,100,000.000e+00 0 10", "+16777216 , 2", "1.2e101", "446,835,273,728 1", "1e36", "1e39", // there isn't a big enough suffix for this one but it's less than googol ] for (test in tests) suffize.call(test)
http://rosettacode.org/wiki/Sum_of_a_series
Sum of a series
Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k = 1 n 1 k 2 {\displaystyle S_{n}=\sum _{k=1}^{n}{\frac {1}{k^{2}}}} and compute   S 1000 {\displaystyle S_{1000}} This approximates the   zeta function   for   S=2,   whose exact value ζ ( 2 ) = π 2 6 {\displaystyle \zeta (2)={\pi ^{2} \over 6}} is the solution of the Basel problem.
#AppleScript
AppleScript
----------------------- SUM OF SERIES ----------------------   -- seriesSum :: Num a => (a -> a) -> [a] -> a on seriesSum(f, xs) script go property mf : |λ| of mReturn(f) on |λ|(a, x) a + mf(x) end |λ| end script   foldl(go, 0, xs) end seriesSum     ---------------------------- TEST --------------------------   -- inverseSquare :: Num -> Num on inverseSquare(x) 1 / (x ^ 2) end inverseSquare   on run seriesSum(inverseSquare, enumFromTo(1, 1000))   --> 1.643934566682 end run     --------------------- GENERIC FUNCTIONS --------------------   -- enumFromTo :: Int -> Int -> [Int] on enumFromTo(m, n) if m ≤ n then set lst to {} repeat with i from m to n set end of lst to i end repeat lst else {} end if end enumFromTo     -- foldl :: (a -> b -> a) -> a -> [b] -> a on foldl(f, startValue, xs) tell mReturn(f) set v to startValue set lng to length of xs repeat with i from 1 to lng set v to |λ|(v, item i of xs, i, xs) end repeat return v end tell end foldl     -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: Handler -> Script on mReturn(f) if class of f is script then f else script property |λ| : f end script end if end mReturn
http://rosettacode.org/wiki/System_time
System time
Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related task   Date format See also   Retrieving system time (wiki)
#Ursa
Ursa
# outputs time in milliseconds import "time" out (time.getcurrent) endl console
http://rosettacode.org/wiki/System_time
System time
Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related task   Date format See also   Retrieving system time (wiki)
#Ursala
Ursala
#import cli   #cast %s   main = now 0
http://rosettacode.org/wiki/Sum_to_100
Sum to 100
Task Find solutions to the   sum to one hundred   puzzle. Add (insert) the mathematical operators     +   or   -     (plus or minus)   before any of the digits in the decimal numeric string   123456789   such that the resulting mathematical expression adds up to a particular sum   (in this iconic case,   100). Example: 123 + 4 - 5 + 67 - 89 = 100 Show all output here.   Show all solutions that sum to   100   Show the sum that has the maximum   number   of solutions   (from zero to infinity‡)   Show the lowest positive sum that   can't   be expressed   (has no solutions),   using the rules for this task   Show the ten highest numbers that can be expressed using the rules for this task   (extra credit) ‡   (where   infinity   would be a relatively small   123,456,789) An example of a sum that can't be expressed   (within the rules of this task)   is:   5074 (which,   of course,   isn't the lowest positive sum that can't be expressed).
#Aime
Aime
integer b, i, j, k, l, p, s, z; index r, w;   i = 0; while (i < 512) { b = i.bcount; j = 0; while (j < 1 << b) { data e;   j += 1;   k = s = p = 0; l = j; z = 1; while (k < 9) { if (i & 1 << k) { e.append("-+"[l & 1]); s += p * z; z = (l & 1) * 2 - 1; l >>= 1; p = 0; } e.append('1' + k); p = p * 10 + 1 + k;   k += 1; }   s += p * z;   if (e[0] != '+') { if (s == 100) { o_(e, "\n"); }   w[s] += 1; } }   i += 1; }   w.wcall(i_fix, 1, 1, r);   o_(r.back, "\n");   k = 0; for (+k in w) { if (!w.key(k + 1)) { o_(k + 1, "\n"); break; } }   i = 10; for (k of w) { o_(k, "\n"); if (!(i -= 1)) { break; } }
http://rosettacode.org/wiki/Sum_multiples_of_3_and_5
Sum multiples of 3 and 5
Task The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n. Show output for n = 1000. This is is the same as Project Euler problem 1. Extra credit: do this efficiently for n = 1e20 or higher.
#AutoHotkey
AutoHotkey
n := 1000   msgbox % "Sum is " . Sum3_5(n) . " for n = " . n msgbox % "Sum is " . Sum3_5_b(n) . " for n = " . n   ;Standard simple Implementation. Sum3_5(n) { sum := 0 loop % n-1 { if (!Mod(a_index,3) || !Mod(a_index,5)) sum:=sum+A_index } return sum }   ;Translated from the C++ version. Sum3_5_b( i ) { sum := 0, a := 0 while (a < 28) { if (!Mod(a,3) || !Mod(a,5)) { sum += a s := 30 while (s < i) { if (a+s < i) sum += (a+s) s+=30 } } a+=1 } return sum }
http://rosettacode.org/wiki/Sum_digits_of_an_integer
Sum digits of an integer
Task Take a   Natural Number   in a given base and return the sum of its digits:   110         sums to   1   123410   sums to   10   fe16       sums to   29   f0e16     sums to   29
#ATS
ATS
  (* ****** ****** *) // // How to compile: // patscc -DATS_MEMALLOC_LIBC -o SumDigits SumDigits.dats // (* ****** ****** *) // #include "share/atspre_staload.hats" // (* ****** ****** *)   extern fun{a:t@ype} SumDigits(n: a, base: int): a   implement {a}(*tmp*) SumDigits(n, base) = let // val base = gnumber_int(base) // fun loop (n: a, res: a): a = if gisgtz_val<a> (n) then loop (gdiv_val<a>(n, base), gadd_val<a>(res, gmod_val<a>(n, base))) else res // in loop (n, gnumber_int(0)) end // end of [SumDigits]   (* ****** ****** *)   val SumDigits_int = SumDigits<int>   (* ****** ****** *)   implement main0 () = { // val n = 1 val () = println! ("SumDigits(1, 10) = ", SumDigits_int(n, 10)) val n = 12345 val () = println! ("SumDigits(12345, 10) = ", SumDigits_int(n, 10)) val n = 123045 val () = println! ("SumDigits(123045, 10) = ", SumDigits_int(n, 10)) val n = 0xfe val () = println! ("SumDigits(0xfe, 16) = ", SumDigits_int(n, 16)) val n = 0xf0e val () = println! ("SumDigits(0xf0e, 16) = ", SumDigits_int(n, 16)) // } (* end of [main0] *)  
http://rosettacode.org/wiki/Sum_of_squares
Sum of squares
Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
#Arturo
Arturo
arr: 1..10   print sum map arr [x][x^2]
http://rosettacode.org/wiki/Sum_of_squares
Sum of squares
Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
#Astro
Astro
sum([1, 2, 3, 4]²)
http://rosettacode.org/wiki/Sum_and_product_of_an_array
Sum and product of an array
Task Compute the sum and product of an array of integers.
#Ada
Ada
type Int_Array is array(Integer range <>) of Integer;   array : Int_Array := (1,2,3,4,5,6,7,8,9,10); Sum : Integer := 0; for I in array'range loop Sum := Sum + array(I); end loop;
http://rosettacode.org/wiki/Sum_and_product_puzzle
Sum and product puzzle
Task[edit] Solve the "Impossible Puzzle": X and Y are two different whole numbers greater than 1. Their sum is no greater than 100, and Y is greater than X. S and P are two mathematicians (and consequently perfect logicians); S knows the sum X+Y and P knows the product X*Y. Both S and P know all the information in this paragraph. The following conversation occurs: S says "P does not know X and Y." P says "Now I know X and Y." S says "Now I also know X and Y!" What are X and Y? Guidance It can be hard to wrap one's head around what the three lines of dialog between S (the "sum guy") and P (the "product guy") convey about the values of X and Y. So for your convenience, here's a break-down: Quote Implied fact 1) S says "P does not know X and Y." For every possible sum decomposition of the number X+Y, the product has in turn more than one product decomposition. 2) P says "Now I know X and Y." The number X*Y has only one product decomposition for which fact 1 is true. 3) S says "Now I also know X and Y." The number X+Y has only one sum decomposition for which fact 2 is true. Terminology: "sum decomposition" of a number = Any pair of positive integers (A, B) so that A+B equals the number. Here, with the additional constraint 2 ≤ A < B. "product decomposition" of a number = Any pair of positive integers (A, B) so that A*B equals the number. Here, with the additional constraint 2 ≤ A < B. Your program can solve the puzzle by considering all possible pairs (X, Y) in the range 2 ≤ X < Y ≤ 98, and then successively eliminating candidates based on the three facts. It turns out only one solution remains! See the Python example for an implementation that uses this approach with a few optimizations. See also   Wikipedia:   Sum and Product Puzzle
#REXX
REXX
debug=0 If debug Then Do oid='sppn.txt'; 'erase' oid End Call time 'R' all_pairs='' cnt.=0 i=0 /* first take all possible pairs 2<=x<y with x+y<=100 */ /* and compute the respective sums and products */ /* count the number of times a sum or product occurs */ Do x=2 To 98 Do y=x+1 To 100-x x=right(x,2,0) y=right(y,2,0) all_pairs=all_pairs x'/'y i=i+1 x.i=x y.i=y sum=x+y prd=x*y cnt.0s.sum=cnt.0s.sum+1 cnt.0p.prd=cnt.0p.prd+1 End End n=i /* now compute the possible pairs for each sum sum_d.sum */ /* and product prd_d.prd */ /* also the list of possible sums and products suml, prdl*/ sum_d.='' prd_d.='' suml='' prdl='' Do i=1 To n x=x.i y=y.i x=right(x,2,0) y=right(y,2,0) sum=x+y prd=x*y cnt.0s.x.y=cnt.0s.sum cnt.0p.x.y=cnt.0p.prd sum_d.sum=sum_d.sum x'/'y prd_d.prd=prd_d.prd x'/'y If wordpos(sum,suml)=0 Then suml=suml sum If wordpos(prd,prdl)=0 Then prdl=prdl prd End Say n 'possible pairs' Call o 'SUM' suml=wordsort(suml) prdl=wordsort(prdl) sumlc=suml si=0 pi=0 Do While sumlc>'' Parse Var sumlc sum sumlc si=si+1 sum.si=sum si.sum=si If sum=17 Then sx=si temp=prdl Do While temp>'' Parse Var temp prd temp If si=1 Then Do pi=pi+1 prd.pi=prd pi.prd=pi If prd=52 Then px=pi End A.prd.sum='+' End End sin=si pin=pi Call o 'SUM' Do si=1 To sin Call o f5(si) f3(sum.si) End Call o 'PRD' Do pi=1 To pin Call o f5(pi) f6(prd.pi) End a.='-' Do pi=1 To pin prd=prd.pi Do si=1 To sin sum=sum.si Do sj=1 To words(sum_d.sum) If wordpos(word(sum_d.sum,sj),prd_d.prd)>0 Then Parse Value word(sum_d.sum,sj) with x '/' y prde=x*y sume=x+y pa=pi.prde sa=si.sume a.pa.sa='+' End End End Call show '1'   Do pi=1 To pin prow='' cnt=0 Do si=1 To sin If a.pi.si='+' Then Do cnt=cnt+1 pj=pi sj=si End End If cnt=1 Then a.pj.sj='1' End Call show '2'   Do si=1 To sin Do pi=1 To pin If a.pi.si='1' Then Leave End If pi<=pin Then Do Do pi=1 To pin If a.pi.si='+' Then a.pi.si='2' End End End Call show '3'   Do pi=1 To pin prow='' Do si=1 To sin prow=prow||a.pi.si End If count('+',prow)>1 Then Do Do si=1 To sin If a.pi.si='+' Then a.pi.si='3' End End End Call show '4'   Do si=1 To sin scol='' Do pi=1 To pin scol=scol||a.pi.si End If count('+',scol)>1 Then Do Do pi=1 To pin If a.pi.si='+' Then a.pi.si='4' End End End Call show '5'   sol=0 Do pi=1 To pin Do si=1 To sin If a.pi.si='+' Then Do Say sum.si prd.pi sum=sum.si prd=prd.pi sol=sol+1 End End End Say sol 'solution(s)' Say ' possible pairs' Say 'Product='prd prd_d.52 Say ' Sum='sum sum_d.17 Say 'The only pair in both lists is 04/13.' Say 'Elapsed time:' time('E') 'seconds' Exit show: If debug Then Do Call o 'show' arg(1) Do pi=1 To 60 ol='' Do si=1 To 60 ol=ol||a.pi.si End Call o ol End Say 'a.'px'.'sx'='a.px.sx End Return   Exit o: Return lineout(oid,arg(1)) f3: Return format(arg(1),3) f4: Return format(arg(1),4) f5: Return format(arg(1),5) f6: Return format(arg(1),6)   count: Procedure Parse Arg c,s s=translate(s,c,c||xrange('00'x,'ff'x)) s=space(s,0) Return length(s) wordsort: Procedure /********************************************************************** * Sort the list of words supplied as argument. Return the sorted list **********************************************************************/ Parse Arg wl wa.='' wa.0=0 Do While wl<>'' Parse Var wl w wl Do i=1 To wa.0 If wa.i>w Then Leave End If i<=wa.0 Then Do Do j=wa.0 To i By -1 ii=j+1 wa.ii=wa.j End End wa.i=w wa.0=wa.0+1 End swl='' Do i=1 To wa.0 swl=swl wa.i End /* Say swl */ Return strip(swl)
http://rosettacode.org/wiki/Suffixation_of_decimal_numbers
Suffixation of decimal numbers
Suffixation:   a letter or a group of letters added to the end of a word to change its meaning.       ─────   or, as used herein   ───── Suffixation:   the addition of a metric or "binary" metric suffix to a number, with/without rounding. Task Write a function(s) to append (if possible)   a metric   or   a "binary" metric   suffix to a number   (displayed in decimal). The number may be rounded   (as per user specification)   (via shortening of the number when the number of digits past the decimal point are to be used). Task requirements   write a function (or functions) to add   (if possible)   a suffix to a number   the function(s) should be able to express the number (possibly with a suffix) in as many decimal digits as specified   the sign should be preserved   (if present)   the number may have commas within the number   (the commas need not be preserved)   the number may have a decimal point and/or an exponent as in:   -123.7e-01   the suffix that might be appended should be in uppercase;   however, the   i   should be in lowercase   support:   the            metric suffixes:   K  M  G  T  P  E  Z  Y  X  W  V  U   the binary metric suffixes:   Ki Mi Gi Ti Pi Ei Zi Yi Xi Wi Vi Ui   the (full name) suffix:   googol   (lowercase)   (equal to 1e100)     (optional)   a number of decimal digits past the decimal point   (with rounding).   The default is to display all significant digits   validation of the (supplied/specified) arguments is optional but recommended   display   (with identifying text):   the original number   (with identifying text)   the number of digits past the decimal point being used   (or none, if not specified)   the type of suffix being used   (metric or "binary" metric)   the (new) number with the appropriate   (if any)   suffix   all output here on this page Metric suffixes to be supported   (whether or not they're officially sanctioned) K multiply the number by 10^3 kilo (1,000) M multiply the number by 10^6 mega (1,000,000) G multiply the number by 10^9 giga (1,000,000,000) T multiply the number by 10^12 tera (1,000,000,000,000) P multiply the number by 10^15 peta (1,000,000,000,000,000) E multiply the number by 10^18 exa (1,000,000,000,000,000,000) Z multiply the number by 10^21 zetta (1,000,000,000,000,000,000,000) Y multiply the number by 10^24 yotta (1,000,000,000,000,000,000,000,000) X multiply the number by 10^27 xenta (1,000,000,000,000,000,000,000,000,000) W multiply the number by 10^30 wekta (1,000,000,000,000,000,000,000,000,000,000) V multiply the number by 10^33 vendeka (1,000,000,000,000,000,000,000,000,000,000,000) U multiply the number by 10^36 udekta (1,000,000,000,000,000,000,000,000,000,000,000,000) "Binary" suffixes to be supported   (whether or not they're officially sanctioned) Ki multiply the number by 2^10 kibi (1,024) Mi multiply the number by 2^20 mebi (1,048,576) Gi multiply the number by 2^30 gibi (1,073,741,824) Ti multiply the number by 2^40 tebi (1,099,571,627,776) Pi multiply the number by 2^50 pebi (1,125,899,906,884,629) Ei multiply the number by 2^60 exbi (1,152,921,504,606,846,976) Zi multiply the number by 2^70 zebi (1,180,591,620,717,411,303,424) Yi multiply the number by 2^80 yobi (1,208,925,819,614,629,174,706,176) Xi multiply the number by 2^90 xebi (1,237,940,039,285,380,274,899,124,224) Wi multiply the number by 2^100 webi (1,267,650,600,228,229,401,496,703,205,376) Vi multiply the number by 2^110 vebi (1,298,074,214,633,706,907,132,624,082,305,024) Ui multiply the number by 2^120 uebi (1,329,227,995,784,915,872,903,807,060,280,344,576) For instance, with this pseudo─code /* 1st arg: the number to be transformed.*/ /* 2nd arg: # digits past the dec. point.*/ /* 3rd arg: the type of suffix to use. */ /* 2 indicates "binary" suffix.*/ /* 10 indicates decimal suffix.*/ a = '456,789,100,000,000' /* "A" has eight trailing zeros. */ say ' aa=' suffize(a) /* Display a suffized number to terminal.*/ /* The "1" below shows one decimal ···*/ /* digit past the decimal point. */ n = suffize(a, 1) /* SUFFIZE is the function name. */ n = suffize(a, 1, 10) /* (identical to the above statement.) */ say ' n=' n /* Display value of N to terminal. */ /* Note the rounding that occurs. */ f = suffize(a, 1, 2) /* SUFFIZE with one fractional digit */ say ' f=' f /* Display value of F to terminal. */ /* Display value in "binary" metric. */ bin = suffize(a, 5, 2) /* SUFFIZE with binary metric suffix. */ say 'bin=' bin /* Display value of BIN to terminal. */ win = suffize(a, 0, 2) /* SUFFIZE with binary metric suffix. */ say 'win=' win /* Display value of WIN to terminal. */ xvi = ' +16777216 ' /* this used to be a big computer ··· */ big = suffize(xvi, , 2) /* SUFFIZE with binary metric suffix. */ say 'big=' big /* Display value of BIG to terminal. */ would display: aa= 456.7891T n= 456.8T f= 415.4Ti bin= 415.44727Ti win= 415Ti big= 16Mi Use these test cases 87,654,321 -998,877,665,544,332,211,000 3 +112,233 0 16,777,216 1 456,789,100,000,000 2 456,789,100,000,000 2 10 456,789,100,000,000 5 2 456,789,100,000.000e+00 0 10 +16777216 , 2 1.2e101 (your primary disk free space) 1 ◄■■■■■■■ optional Use whatever parameterizing your computer language supports,   and it's permitted to create as many separate functions as are needed   (if needed)   if   function arguments aren't allowed to be omitted or varied. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#zkl
zkl
var [const] BI=Import.lib("zklBigNum"); // GMP var metric, binary, googol=BI("1e100"); metric,binary = metricBin();   // suffix: "2" (binary), "10" (metric) // For this task, we'll assume BF numbers and treat everything as a big int fcn sufficate(numStr, fracDigits=",", suffix="10"){ var [const] numRE=RegExp(0'^\+*(([+-]*\.*\d+)[.]*(\d*)(e*[+-]*\d*))^);   numRE.search((numStr - " ,").toLower()); r:=numRE.matched[1]; if(not r.find(".")) r=BI(r); // else ((((0,7),"1.2e101","1","2","e101") else // convert float ("1.2" or "1.2e10") to big int r=BI(numRE.matched[2,*].concat())/(10).pow(numRE.matched[3].len());   if(fracDigits==",") fracDigits=0; # "digits past decimal or none, if not specified" else fracDigits=fracDigits.toInt();   suffix=suffix.strip().toInt(); if(suffix==2) nms,szs :=binary; else if(suffix==10) nms,szs :=metric; else //throw(Exception.ValueError("Invalid suffix: %s".fmt(suffix))); return("Invalid suffix");   ar:=r.abs(); if(ar<szs[0]) return(r.toString()); // little bitty number i,sz,nm := szs.filter1n('>(ar)) - 1, szs[i], nms[i]; // False - 1 == True if(i==True) // r > biggest unit if(r>=googol) sz,nm = googol, "googol"; // get out the big hammer else sz,nm = szs[-1], nms[-1]; // even if they want n^2 fd,m := fracDigits + 4, BI(10).pow(fd); // int --> float w/extra digits a,f,a := r*m/sz, (a%m).toFloat()/m, f + a/m; // to float for rounding fmt:="%%,.%df%%s".fmt(fracDigits).fmt; // eg "%,.5f%s" return(fmt(a,nm)); }   //-->Metric:(("K", "M",..), (1000,1000000,..)) // Bin: (("Ki","Mi",..),(1024,1048576,..)) fcn metricBin{ ss,m,b := "K M G T P E Z Y X W V U".split(), List(),List(); ss.zipWith(m.append,[3..3*(ss.len()),3].apply(BI(10).pow)); // Metric ss.apply("append","i") .zipWith(b.append,[10..10*(ss.len()),10].apply(BI(2).pow)); // Binary return(m.filter22("".isType), b.filter22("".isType)); # split to ((strings),(nums)) }
http://rosettacode.org/wiki/Sum_of_a_series
Sum of a series
Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k = 1 n 1 k 2 {\displaystyle S_{n}=\sum _{k=1}^{n}{\frac {1}{k^{2}}}} and compute   S 1000 {\displaystyle S_{1000}} This approximates the   zeta function   for   S=2,   whose exact value ζ ( 2 ) = π 2 6 {\displaystyle \zeta (2)={\pi ^{2} \over 6}} is the solution of the Basel problem.
#Arturo
Arturo
series: map 1..1000 => [1.0/&^2] print [sum series]
http://rosettacode.org/wiki/System_time
System time
Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related task   Date format See also   Retrieving system time (wiki)
#Vala
Vala
  var now = new DateTime.now_local(); string now_string = now.to_string();
http://rosettacode.org/wiki/System_time
System time
Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related task   Date format See also   Retrieving system time (wiki)
#VBA
VBA
Debug.Print Now()
http://rosettacode.org/wiki/Sum_to_100
Sum to 100
Task Find solutions to the   sum to one hundred   puzzle. Add (insert) the mathematical operators     +   or   -     (plus or minus)   before any of the digits in the decimal numeric string   123456789   such that the resulting mathematical expression adds up to a particular sum   (in this iconic case,   100). Example: 123 + 4 - 5 + 67 - 89 = 100 Show all output here.   Show all solutions that sum to   100   Show the sum that has the maximum   number   of solutions   (from zero to infinity‡)   Show the lowest positive sum that   can't   be expressed   (has no solutions),   using the rules for this task   Show the ten highest numbers that can be expressed using the rules for this task   (extra credit) ‡   (where   infinity   would be a relatively small   123,456,789) An example of a sum that can't be expressed   (within the rules of this task)   is:   5074 (which,   of course,   isn't the lowest positive sum that can't be expressed).
#ALGOL_68
ALGOL 68
BEGIN # find the numbers the string 123456789 ( with "+/-" optionally inserted # # before each digit ) can generate #   # experimentation shows that the largest hundred numbers that can be # # generated are are greater than or equal to 56795 # # as we can't declare an array with bounds -123456789 : 123456789 in # # Algol 68G, we use -60000 : 60000 and keep counts for the top hundred #   INT max number = 60 000; [ - max number : max number ]STRING solutions; [ - max number : max number ]INT count; FOR i FROM LWB solutions TO UPB solutions DO solutions[ i ] := ""; count[ i ] := 0 OD;   # calculate the numbers ( up to max number ) we can generate and the strings leading to them # # also determine the largest numbers we can generate # [ 100 ]INT largest; [ 100 ]INT largest count; INT impossible number = - 999 999 999; FOR i FROM LWB largest TO UPB largest DO largest [ i ] := impossible number; largest count[ i ] := 0 OD; [ 1 : 18 ]CHAR sum string := ".1.2.3.4.5.6.7.8.9"; []CHAR sign char = []CHAR( "-", " ", "+" )[ AT -1 ]; # we don't distinguish between strings starting "+1" and starting " 1" # FOR s1 FROM -1 TO 0 DO sum string[ 1 ] := sign char[ s1 ]; FOR s2 FROM -1 TO 1 DO sum string[ 3 ] := sign char[ s2 ]; FOR s3 FROM -1 TO 1 DO sum string[ 5 ] := sign char[ s3 ]; FOR s4 FROM -1 TO 1 DO sum string[ 7 ] := sign char[ s4 ]; FOR s5 FROM -1 TO 1 DO sum string[ 9 ] := sign char[ s5 ]; FOR s6 FROM -1 TO 1 DO sum string[ 11 ] := sign char[ s6 ]; FOR s7 FROM -1 TO 1 DO sum string[ 13 ] := sign char[ s7 ]; FOR s8 FROM -1 TO 1 DO sum string[ 15 ] := sign char[ s8 ]; FOR s9 FROM -1 TO 1 DO sum string[ 17 ] := sign char[ s9 ]; INT number := 0; INT part := IF s1 < 0 THEN -1 ELSE 1 FI; IF s2 = 0 THEN part *:= 10 +:= 2 * SIGN part ELSE number +:= part; part := 2 * s2 FI; IF s3 = 0 THEN part *:= 10 +:= 3 * SIGN part ELSE number +:= part; part := 3 * s3 FI; IF s4 = 0 THEN part *:= 10 +:= 4 * SIGN part ELSE number +:= part; part := 4 * s4 FI; IF s5 = 0 THEN part *:= 10 +:= 5 * SIGN part ELSE number +:= part; part := 5 * s5 FI; IF s6 = 0 THEN part *:= 10 +:= 6 * SIGN part ELSE number +:= part; part := 6 * s6 FI; IF s7 = 0 THEN part *:= 10 +:= 7 * SIGN part ELSE number +:= part; part := 7 * s7 FI; IF s8 = 0 THEN part *:= 10 +:= 8 * SIGN part ELSE number +:= part; part := 8 * s8 FI; IF s9 = 0 THEN part *:= 10 +:= 9 * SIGN part ELSE number +:= part; part := 9 * s9 FI; number +:= part; IF number >= LWB solutions AND number <= UPB solutions THEN solutions[ number ] +:= ";" + sum string; count [ number ] +:= 1 FI; BOOL inserted := FALSE; FOR l pos FROM LWB largest TO UPB largest WHILE NOT inserted DO IF number > largest[ l pos ] THEN # found a new larger number # FOR m pos FROM UPB largest BY -1 TO l pos + 1 DO largest [ m pos ] := largest [ m pos - 1 ]; largest count[ m pos ] := largest count[ m pos - 1 ] OD; largest [ l pos ] := number; largest count[ l pos ] := 1; inserted := TRUE ELIF number = largest[ l pos ] THEN # have another way of generating this number # largest count[ l pos ] +:= 1; inserted := TRUE FI OD OD OD OD OD OD OD OD OD OD;   # show the solutions for 100 # print( ( "100 has ", whole( count[ 100 ], 0 ), " solutions:" ) ); STRING s := solutions[ 100 ]; FOR s pos FROM LWB s TO UPB s DO IF s[ s pos ] = ";" THEN print( ( newline, " " ) ) ELIF s[ s pos ] /= " " THEN print( ( s[ s pos ] ) ) FI OD; print( ( newline ) ); # find the number with the most solutions # INT max solutions := 0; INT number with max := LWB count - 1; FOR n FROM 0 TO max number DO IF count[ n ] > max solutions THEN max solutions := count[ n ]; number with max := n FI OD; FOR n FROM LWB largest count TO UPB largest count DO IF largest count[ n ] > max solutions THEN max solutions := largest count[ n ]; number with max := largest[ n ] FI OD; print( ( whole( number with max, 0 ), " has the maximum number of solutions: ", whole( max solutions, 0 ), newline ) ); # find the smallest positive number that has no solutions # BOOL have solutions := TRUE; FOR n FROM 0 TO max number WHILE IF NOT ( have solutions := count[ n ] > 0 ) THEN print( ( whole( n, 0 ), " is the lowest positive number with no solutions", newline ) ) FI; have solutions DO SKIP OD; IF have solutions THEN print( ( "All positive numbers up to ", whole( max number, 0 ), " have solutions", newline ) ) FI; print( ( "The 10 largest numbers that can be generated are:", newline ) ); FOR t pos FROM 1 TO 10 DO print( ( " ", whole( largest[ t pos ], 0 ) ) ) OD; print( ( newline ) )   END
http://rosettacode.org/wiki/Sum_multiples_of_3_and_5
Sum multiples of 3 and 5
Task The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n. Show output for n = 1000. This is is the same as Project Euler problem 1. Extra credit: do this efficiently for n = 1e20 or higher.
#AWK
AWK
#!/usr/bin/awk -f { n = $1-1; print sum(n,3)+sum(n,5)-sum(n,15); } function sum(n,d) { m = int(n/d); return (d*m*(m+1)/2); }
http://rosettacode.org/wiki/Sum_digits_of_an_integer
Sum digits of an integer
Task Take a   Natural Number   in a given base and return the sum of its digits:   110         sums to   1   123410   sums to   10   fe16       sums to   29   f0e16     sums to   29
#AutoHotkey
AutoHotkey
MsgBox % sprintf("%d %d %d %d %d`n" ,SumDigits(1, 10) ,SumDigits(12345, 10) ,SumDigits(123045, 10) ,SumDigits(0xfe, 16) ,SumDigits(0xf0e, 16) )   SumDigits(n,base) { sum := 0 while (n) { sum += Mod(n,base) n /= base } return sum }   sprintf(s,fmt*) { for each, f in fmt StringReplace,s,s,`%d, % f return s }
http://rosettacode.org/wiki/Sum_of_squares
Sum of squares
Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
#Asymptote
Asymptote
int suma; int[] a={1, 2, 3, 4, 5, 6};   for(var i : a) suma = suma + a[i] ^ 2;   write("The sum of squares is: ", suma);
http://rosettacode.org/wiki/Sum_of_squares
Sum of squares
Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
#AutoHotkey
AutoHotkey
list = 3 1 4 1 5 9 Loop, Parse, list, %A_Space% sum += A_LoopField**2 MsgBox,% sum
http://rosettacode.org/wiki/Sum_and_product_of_an_array
Sum and product of an array
Task Compute the sum and product of an array of integers.
#Aime
Aime
void compute(integer &s, integer &p, list l) { integer v;   s = 0; p = 1; for (, v in l) { s += v; p *= v; } }   integer main(void) { integer sum, product;   compute(sum, product, list(2, 3, 5, 7, 11, 13, 17, 19));   o_form("~\n~\n", sum, product);   return 0; }
http://rosettacode.org/wiki/Sum_and_product_of_an_array
Sum and product of an array
Task Compute the sum and product of an array of integers.
#ALGOL_68
ALGOL 68
main:( INT default upb := 3; MODE INTARRAY = [default upb]INT;   INTARRAY array = (1,2,3,4,5,6,7,8,9,10); INT sum := 0; FOR i FROM LWB array TO UPB array DO sum +:= array[i] OD;   # Define the product function # PROC int product = (INTARRAY item)INT: ( INT prod :=1; FOR i FROM LWB item TO UPB item DO prod *:= item[i] OD; prod ) # int product # ; printf(($" Sum: "g(0)$,sum,$", Product:"g(0)";"l$,int product(array))) )
http://rosettacode.org/wiki/Sum_and_product_puzzle
Sum and product puzzle
Task[edit] Solve the "Impossible Puzzle": X and Y are two different whole numbers greater than 1. Their sum is no greater than 100, and Y is greater than X. S and P are two mathematicians (and consequently perfect logicians); S knows the sum X+Y and P knows the product X*Y. Both S and P know all the information in this paragraph. The following conversation occurs: S says "P does not know X and Y." P says "Now I know X and Y." S says "Now I also know X and Y!" What are X and Y? Guidance It can be hard to wrap one's head around what the three lines of dialog between S (the "sum guy") and P (the "product guy") convey about the values of X and Y. So for your convenience, here's a break-down: Quote Implied fact 1) S says "P does not know X and Y." For every possible sum decomposition of the number X+Y, the product has in turn more than one product decomposition. 2) P says "Now I know X and Y." The number X*Y has only one product decomposition for which fact 1 is true. 3) S says "Now I also know X and Y." The number X+Y has only one sum decomposition for which fact 2 is true. Terminology: "sum decomposition" of a number = Any pair of positive integers (A, B) so that A+B equals the number. Here, with the additional constraint 2 ≤ A < B. "product decomposition" of a number = Any pair of positive integers (A, B) so that A*B equals the number. Here, with the additional constraint 2 ≤ A < B. Your program can solve the puzzle by considering all possible pairs (X, Y) in the range 2 ≤ X < Y ≤ 98, and then successively eliminating candidates based on the three facts. It turns out only one solution remains! See the Python example for an implementation that uses this approach with a few optimizations. See also   Wikipedia:   Sum and Product Puzzle
#Ruby
Ruby
def add(x,y) x + y end def mul(x,y) x * y end   def sumEq(s,p) s.select{|q| add(*p) == add(*q)} end def mulEq(s,p) s.select{|q| mul(*p) == mul(*q)} end   s1 = (a = *2...100).product(a).select{|x,y| x<y && x+y<100} s2 = s1.select{|p| sumEq(s1,p).all?{|q| mulEq(s1,q).size != 1} } s3 = s2.select{|p| (mulEq(s1,p) & s2).size == 1} p s3.select{|p| (sumEq(s1,p) & s3).size == 1}
http://rosettacode.org/wiki/Sum_of_a_series
Sum of a series
Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k = 1 n 1 k 2 {\displaystyle S_{n}=\sum _{k=1}^{n}{\frac {1}{k^{2}}}} and compute   S 1000 {\displaystyle S_{1000}} This approximates the   zeta function   for   S=2,   whose exact value ζ ( 2 ) = π 2 6 {\displaystyle \zeta (2)={\pi ^{2} \over 6}} is the solution of the Basel problem.
#AutoHotkey
AutoHotkey
SetFormat, FloatFast, 0.15 While A_Index <= 1000 sum += 1/A_Index**2 MsgBox,% sum ;1.643934566681554
http://rosettacode.org/wiki/System_time
System time
Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related task   Date format See also   Retrieving system time (wiki)
#VBScript
VBScript
WScript.Echo Now
http://rosettacode.org/wiki/System_time
System time
Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related task   Date format See also   Retrieving system time (wiki)
#Vlang
Vlang
import time   fn main() { t := time.Now() println(t) // default format YYYY-MM-DD HH:MM:SS println(t.custom_format("ddd MMM d HH:mm:ss YYYY")) // some custom format }
http://rosettacode.org/wiki/Sum_to_100
Sum to 100
Task Find solutions to the   sum to one hundred   puzzle. Add (insert) the mathematical operators     +   or   -     (plus or minus)   before any of the digits in the decimal numeric string   123456789   such that the resulting mathematical expression adds up to a particular sum   (in this iconic case,   100). Example: 123 + 4 - 5 + 67 - 89 = 100 Show all output here.   Show all solutions that sum to   100   Show the sum that has the maximum   number   of solutions   (from zero to infinity‡)   Show the lowest positive sum that   can't   be expressed   (has no solutions),   using the rules for this task   Show the ten highest numbers that can be expressed using the rules for this task   (extra credit) ‡   (where   infinity   would be a relatively small   123,456,789) An example of a sum that can't be expressed   (within the rules of this task)   is:   5074 (which,   of course,   isn't the lowest positive sum that can't be expressed).
#AppleScript
AppleScript
use framework "Foundation" -- for basic NSArray sort   property pSigns : {1, 0, -1} --> ( + | unsigned | - ) property plst100 : {"Sums to 100:", ""} property plstSums : {} property plstSumsSorted : missing value property plstSumGroups : missing value   -- data Sign :: [ 1 | 0 | -1 ] = ( Plus | Unsigned | Minus ) -- asSum :: [Sign] -> Int on asSum(xs) script on |λ|(a, sign, i) if sign ≠ 0 then {digits:{}, n:(n of a) + (sign * ((i & digits of a) as string as integer))} else {digits:{i} & (digits of a), n:n of a} end if end |λ| end script   set rec to foldr(result, {digits:{}, n:0}, xs) set ds to digits of rec if length of ds > 0 then (n of rec) + (ds as string as integer) else n of rec end if end asSum   -- data Sign :: [ 1 | 0 | -1 ] = ( Plus | Unisigned | Minus ) -- asString :: [Sign] -> String on asString(xs) script on |λ|(a, sign, i) set d to i as string if sign ≠ 0 then if sign > 0 then a & " +" & d else a & " -" & d end if else a & d end if end |λ| end script   foldl(result, "", xs) end asString   -- sumsTo100 :: () -> String on sumsTo100() -- From first permutation without leading '+' (3 ^ 8) to end of universe (3 ^ 9) repeat with i from 6561 to 19683 set xs to nthPermutationWithRepn(pSigns, 9, i) if asSum(xs) = 100 then set end of plst100 to asString(xs) end repeat intercalate(linefeed, plst100) end sumsTo100     -- mostCommonSum :: () -> String on mostCommonSum() -- From first permutation without leading '+' (3 ^ 8) to end of universe (3 ^ 9) repeat with i from 6561 to 19683 set intSum to asSum(nthPermutationWithRepn(pSigns, 9, i)) if intSum ≥ 0 then set end of plstSums to intSum end repeat   set plstSumsSorted to sort(plstSums) set plstSumGroups to group(plstSumsSorted)   script groupLength on |λ|(a, b) set intA to length of a set intB to length of b if intA < intB then -1 else if intA > intB then 1 else 0 end if end |λ| end script   set lstMaxSum to maximumBy(groupLength, plstSumGroups) intercalate(linefeed, ¬ {"Most common sum: " & item 1 of lstMaxSum, ¬ "Number of instances: " & length of lstMaxSum}) end mostCommonSum     -- TEST ---------------------------------------------------------------------- on run return sumsTo100()   -- Also returns a value, but slow: -- mostCommonSum() end run     -- GENERIC FUNCTIONS ---------------------------------------------------------   -- nthPermutationWithRepn :: [a] -> Int -> Int -> [a] on nthPermutationWithRepn(xs, groupSize, iIndex) set intBase to length of xs set intSetSize to intBase ^ groupSize   if intBase < 1 or iIndex > intSetSize then {} else set baseElems to inBaseElements(xs, iIndex) set intZeros to groupSize - (length of baseElems)   if intZeros > 0 then replicate(intZeros, item 1 of xs) & baseElems else baseElems end if end if end nthPermutationWithRepn   -- inBaseElements :: [a] -> Int -> [String] on inBaseElements(xs, n) set intBase to length of xs   script nextDigit on |λ|(residue) set {divided, remainder} to quotRem(residue, intBase)   {valid:divided > 0, value:(item (remainder + 1) of xs), new:divided} end |λ| end script   reverse of unfoldr(nextDigit, n) end inBaseElements   -- sort :: [a] -> [a] on sort(lst) ((current application's NSArray's arrayWithArray:lst)'s ¬ sortedArrayUsingSelector:"compare:") as list end sort   -- maximumBy :: (a -> a -> Ordering) -> [a] -> a on maximumBy(f, xs) set cmp to mReturn(f) script max on |λ|(a, b) if a is missing value or cmp's |λ|(a, b) < 0 then b else a end if end |λ| end script   foldl(max, missing value, xs) end maximumBy   -- group :: Eq a => [a] -> [[a]] on group(xs) script eq on |λ|(a, b) a = b end |λ| end script   groupBy(eq, xs) end group   -- groupBy :: (a -> a -> Bool) -> [a] -> [[a]] on groupBy(f, xs) set mf to mReturn(f)   script enGroup on |λ|(a, x) if length of (active of a) > 0 then set h to item 1 of active of a else set h to missing value end if   if h is not missing value and mf's |λ|(h, x) then {active:(active of a) & x, sofar:sofar of a} else {active:{x}, sofar:(sofar of a) & {active of a}} end if end |λ| end script   if length of xs > 0 then set dct to foldl(enGroup, {active:{item 1 of xs}, sofar:{}}, tail(xs)) if length of (active of dct) > 0 then sofar of dct & {active of dct} else sofar of dct end if else {} end if end groupBy   -- tail :: [a] -> [a] on tail(xs) if length of xs > 1 then items 2 thru -1 of xs else {} end if end tail     -- intercalate :: Text -> [Text] -> Text on intercalate(strText, lstText) set {dlm, my text item delimiters} to {my text item delimiters, strText} set strJoined to lstText as text set my text item delimiters to dlm return strJoined end intercalate   -- quotRem :: Integral a => a -> a -> (a, a) on quotRem(m, n) {m div n, m mod n} end quotRem   -- replicate :: Int -> a -> [a] on replicate(n, a) set out to {} if n < 1 then return out set dbl to {a}   repeat while (n > 1) if (n mod 2) > 0 then set out to out & dbl set n to (n div 2) set dbl to (dbl & dbl) end repeat return out & dbl end replicate   -- foldr :: (a -> b -> a) -> a -> [b] -> a on foldr(f, startValue, xs) tell mReturn(f) set v to startValue set lng to length of xs repeat with i from lng to 1 by -1 set v to |λ|(v, item i of xs, i, xs) end repeat return v end tell end foldr   -- foldl :: (a -> b -> a) -> a -> [b] -> a on foldl(f, startValue, xs) tell mReturn(f) set v to startValue set lng to length of xs repeat with i from 1 to lng set v to |λ|(v, item i of xs, i, xs) end repeat return v end tell end foldl   -- unfoldr :: (b -> Maybe (a, b)) -> b -> [a] on unfoldr(f, v) set mf to mReturn(f) set lst to {} set recM to mf's |λ|(v) repeat while (valid of recM) is true set end of lst to value of recM set recM to mf's |λ|(new of recM) end repeat lst & value of recM end unfoldr   -- until :: (a -> Bool) -> (a -> a) -> a -> a on |until|(p, f, x) set mp to mReturn(p) set v to x   tell mReturn(f) repeat until mp's |λ|(v) set v to |λ|(v) end repeat end tell return v end |until|   -- map :: (a -> b) -> [a] -> [b] on map(f, xs) tell mReturn(f) set lng to length of xs set lst to {} repeat with i from 1 to lng set end of lst to |λ|(item i of xs, i, xs) end repeat return lst end tell end map     -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: Handler -> Script on mReturn(f) if class of f is script then f else script property |λ| : f end script end if end mReturn
http://rosettacode.org/wiki/Sum_multiples_of_3_and_5
Sum multiples of 3 and 5
Task The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n. Show output for n = 1000. This is is the same as Project Euler problem 1. Extra credit: do this efficiently for n = 1e20 or higher.
#BASIC
BASIC
Declare function mulsum35(n as integer) as integer Function mulsum35(n as integer) as integer Dim s as integer For i as integer = 1 to n - 1 If (i mod 3 = 0) or (i mod 5 = 0) then s += i End if Next i Return s End Function Print mulsum35(1000) Sleep End
http://rosettacode.org/wiki/Sum_digits_of_an_integer
Sum digits of an integer
Task Take a   Natural Number   in a given base and return the sum of its digits:   110         sums to   1   123410   sums to   10   fe16       sums to   29   f0e16     sums to   29
#AWK
AWK
#!/usr/bin/awk -f   BEGIN { print sumDigits("1") print sumDigits("12") print sumDigits("fe") print sumDigits("f0e") }   function sumDigits(num, nDigs, digits, sum, d, dig, val, sum) { nDigs = split(num, digits, "") sum = 0 for (d = 1; d <= nDigs; d++) { dig = digits[d] val = digToDec(dig) sum += val } return sum }   function digToDec(dig) { return index("0123456789abcdef", tolower(dig)) - 1 }  
http://rosettacode.org/wiki/Sum_of_squares
Sum of squares
Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
#AWK
AWK
$ awk '{s=0;for(i=1;i<=NF;i++)s+=$i*$i;print s}' 3 1 4 1 5 9 133   0
http://rosettacode.org/wiki/Sum_of_squares
Sum of squares
Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
#BASIC
BASIC
sum = 0 FOR I = LBOUND(a) TO UBOUND(a) sum = sum + a(I) ^ 2 NEXT I PRINT "The sum of squares is: " + sum
http://rosettacode.org/wiki/Sum_and_product_of_an_array
Sum and product of an array
Task Compute the sum and product of an array of integers.
#ALGOL_W
ALGOL W
begin    % computes the sum and product of intArray  %  % the results are returned in sum and product  %  % the bounds of the array must be specified in lb and ub  % procedure sumAndProduct( integer array intArray ( * )  ; integer value lb, ub  ; integer result sum, product ) ; begin   sum  := 0; product := 1;   for i := lb until ub do begin sum  := sum + intArray( i ); product := product * intArray( i ); end for_i ;   end sumAndProduct ;    % test the sumAndProduct procedure  % begin   integer array v ( 1 :: 10 ); integer sum, product;   for i := 1 until 10 do v( i ) := i;   sumAndProduct( v, 1, 10, sum, product ); write( sum, product ); end end.
http://rosettacode.org/wiki/Sum_and_product_puzzle
Sum and product puzzle
Task[edit] Solve the "Impossible Puzzle": X and Y are two different whole numbers greater than 1. Their sum is no greater than 100, and Y is greater than X. S and P are two mathematicians (and consequently perfect logicians); S knows the sum X+Y and P knows the product X*Y. Both S and P know all the information in this paragraph. The following conversation occurs: S says "P does not know X and Y." P says "Now I know X and Y." S says "Now I also know X and Y!" What are X and Y? Guidance It can be hard to wrap one's head around what the three lines of dialog between S (the "sum guy") and P (the "product guy") convey about the values of X and Y. So for your convenience, here's a break-down: Quote Implied fact 1) S says "P does not know X and Y." For every possible sum decomposition of the number X+Y, the product has in turn more than one product decomposition. 2) P says "Now I know X and Y." The number X*Y has only one product decomposition for which fact 1 is true. 3) S says "Now I also know X and Y." The number X+Y has only one sum decomposition for which fact 2 is true. Terminology: "sum decomposition" of a number = Any pair of positive integers (A, B) so that A+B equals the number. Here, with the additional constraint 2 ≤ A < B. "product decomposition" of a number = Any pair of positive integers (A, B) so that A*B equals the number. Here, with the additional constraint 2 ≤ A < B. Your program can solve the puzzle by considering all possible pairs (X, Y) in the range 2 ≤ X < Y ≤ 98, and then successively eliminating candidates based on the three facts. It turns out only one solution remains! See the Python example for an implementation that uses this approach with a few optimizations. See also   Wikipedia:   Sum and Product Puzzle
#Scala
Scala
object ImpossiblePuzzle extends App { type XY = (Int, Int) val step0 = for { x <- 1 to 100 y <- 1 to 100 if 1 < x && x < y && x + y < 100 } yield (x, y)   def sum(xy: XY) = xy._1 + xy._2 def prod(xy: XY) = xy._1 * xy._2 def sumEq(xy: XY) = step0 filter { sum(_) == sum(xy) } def prodEq(xy: XY) = step0 filter { prod(_) == prod(xy) }   val step2 = step0 filter { sumEq(_) forall { prodEq(_).size != 1 }} val step3 = step2 filter { prodEq(_).intersect(step2).size == 1 } val step4 = step3 filter { sumEq(_).intersect(step3).size == 1 } println(step4) }
http://rosettacode.org/wiki/Sum_of_a_series
Sum of a series
Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k = 1 n 1 k 2 {\displaystyle S_{n}=\sum _{k=1}^{n}{\frac {1}{k^{2}}}} and compute   S 1000 {\displaystyle S_{1000}} This approximates the   zeta function   for   S=2,   whose exact value ζ ( 2 ) = π 2 6 {\displaystyle \zeta (2)={\pi ^{2} \over 6}} is the solution of the Basel problem.
#AWK
AWK
$ awk 'BEGIN{for(i=1;i<=1000;i++)s+=1/(i*i);print s}' 1.64393
http://rosettacode.org/wiki/System_time
System time
Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related task   Date format See also   Retrieving system time (wiki)
#Wren
Wren
import "os" for Process import "/date" for Date   var args = Process.arguments if (args.count != 1) Fiber.abort("Please pass the current time in hh:mm:ss format.") var startTime = Date.parse(args[0], Date.isoTime) for (i in 0..1e8) {} // do something which takes a bit of time var now = startTime.addMillisecs((System.clock * 1000).round) Date.default = Date.isoTime + "|.|ttt" System.print("Time now is %(now)")
http://rosettacode.org/wiki/System_time
System time
Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related task   Date format See also   Retrieving system time (wiki)
#XPL0
XPL0
include c:\cxpl\codes; \include intrinsic 'code' declarations   proc NumOut(N); \Output a 2-digit number, including leading zero int N; [if N <= 9 then ChOut(0, ^0); IntOut(0, N); ]; \NumOut   int Reg; [Reg:= GetReg; \get address of array with copy of CPU registers Reg(0):= $2C00; \call DOS function 2C (hex) SoftInt($21); \DOS calls are interrupt 21 (hex) NumOut(Reg(2) >> 8); \the high byte of register CX contains the hours ChOut(0, ^:); NumOut(Reg(2) & $00FF); \the low byte of CX contains the minutes ChOut(0, ^:); NumOut(Reg(3) >> 8); \the high byte of DX contains the seconds ChOut(0, ^.); NumOut(Reg(3) & $00FF); \the low byte of DX contains hundreths CrLf(0); ]
http://rosettacode.org/wiki/Sum_to_100
Sum to 100
Task Find solutions to the   sum to one hundred   puzzle. Add (insert) the mathematical operators     +   or   -     (plus or minus)   before any of the digits in the decimal numeric string   123456789   such that the resulting mathematical expression adds up to a particular sum   (in this iconic case,   100). Example: 123 + 4 - 5 + 67 - 89 = 100 Show all output here.   Show all solutions that sum to   100   Show the sum that has the maximum   number   of solutions   (from zero to infinity‡)   Show the lowest positive sum that   can't   be expressed   (has no solutions),   using the rules for this task   Show the ten highest numbers that can be expressed using the rules for this task   (extra credit) ‡   (where   infinity   would be a relatively small   123,456,789) An example of a sum that can't be expressed   (within the rules of this task)   is:   5074 (which,   of course,   isn't the lowest positive sum that can't be expressed).
#AutoHotkey
AutoHotkey
output:="" for k, v in (sum2num(100)) output .= k "`n" MsgBox, 262144, , % output   mx := [] loop 123456789{ x := sum2num(A_Index) mx[x.Count()] := mx[x.Count()] ? mx[x.Count()] ", " A_Index : A_Index } MsgBox, 262144, , % mx[mx.MaxIndex()] " has " mx.MaxIndex() " solutions"   loop { if !sum2num(A_Index).Count(){ MsgBox, 262144, , % "Lowest positive sum that can't be expressed is " A_Index break } } return   sum2num(num){ output := [] loop % 6561 { oper := SubStr("00000000" ConvertBase(10, 3, A_Index-1), -7) oper := StrReplace(oper, 0, "+") oper := StrReplace(oper, 1, "-") oper := StrReplace(oper, 2, ".") str := "" loop 9 str .= A_Index . SubStr(oper, A_Index, 1) str := StrReplace(str, ".") loop 2 { val := 0 for i, v in StrSplit(str, "+") for j, m in StrSplit(v, "-") val += A_Index=1 ? m : 0-m if (val = num) output[str] := true str := "-" str } } Sort, output return output }   ; https://www.autohotkey.com/boards/viewtopic.php?p=21143&sid=02b9c92ea98737f1db6067b80a2a59cd#p21143 ConvertBase(InputBase, OutputBase, nptr){ static u := A_IsUnicode ? "_wcstoui64" : "_strtoui64" static v := A_IsUnicode ? "_i64tow"  : "_i64toa" VarSetCapacity(s, 66, 0) value := DllCall("msvcrt.dll\" u, "Str", nptr, "UInt", 0, "UInt", InputBase, "CDECL Int64") DllCall("msvcrt.dll\" v, "Int64", value, "Str", s, "UInt", OutputBase, "CDECL") return s }
http://rosettacode.org/wiki/Sum_multiples_of_3_and_5
Sum multiples of 3 and 5
Task The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n. Show output for n = 1000. This is is the same as Project Euler problem 1. Extra credit: do this efficiently for n = 1e20 or higher.
#bc
bc
define t(n, f) { auto m   m = (n - 1) / f return(f * m * (m + 1) / 2) }   define s(l) { return(t(l, 3) + t(l, 5) - t(l, 15)) }   s(1000) s(10 ^ 20)
http://rosettacode.org/wiki/Sum_digits_of_an_integer
Sum digits of an integer
Task Take a   Natural Number   in a given base and return the sum of its digits:   110         sums to   1   123410   sums to   10   fe16       sums to   29   f0e16     sums to   29
#BASIC
BASIC
FUNCTION sumDigits(num AS STRING, bas AS LONG) AS LONG 'can handle up to base 36 DIM outp AS LONG DIM validNums AS STRING, tmp AS LONG, x AS LONG, lennum AS LONG, L0 AS LONG 'ensure num contains only valid characters validNums = LEFT$("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ", bas) lennum = LEN(num) FOR L0 = lennum TO 1 STEP -1 x = INSTR(validNums, UCASE$(MID$(num, L0, 1))) - 1 IF -1 = x THEN EXIT FUNCTION tmp = tmp + (x * (bas ^ (lennum - L0))) NEXT WHILE tmp outp = outp + (tmp MOD bas) tmp = tmp \ bas WEND sumDigits = outp END FUNCTION   PRINT sumDigits(LTRIM$(STR$(1)), 10) PRINT sumDigits(LTRIM$(STR$(1234)), 10) PRINT sumDigits(LTRIM$(STR$(&HFE)), 16) PRINT sumDigits(LTRIM$(STR$(&HF0E)), 16) PRINT sumDigits("2", 2)
http://rosettacode.org/wiki/Sum_of_squares
Sum of squares
Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
#bc
bc
define s(a[], n) { auto i, s   for (i = 0; i < n; i++) { s += a[i] * a[i] }   return(s) }
http://rosettacode.org/wiki/Sum_of_squares
Sum of squares
Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
#BCPL
BCPL
get "libhdr"   let sumsquares(v, len) = len=0 -> 0,  !v * !v + sumsquares(v+1, len-1)   let start() be $( let vector = table 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 writef("%N*N", sumsquares(vector, 10)) $)
http://rosettacode.org/wiki/Sum_and_product_of_an_array
Sum and product of an array
Task Compute the sum and product of an array of integers.
#APL
APL
sum ← +/ prod ← ×/   list ← 1 2 3 4 5   sum list 15   prod list 120
http://rosettacode.org/wiki/Sum_and_product_of_an_array
Sum and product of an array
Task Compute the sum and product of an array of integers.
#AppleScript
AppleScript
set array to {1, 2, 3, 4, 5} set sum to 0 set product to 1 repeat with i in array set sum to sum + i set product to product * i end repeat
http://rosettacode.org/wiki/Sum_and_product_puzzle
Sum and product puzzle
Task[edit] Solve the "Impossible Puzzle": X and Y are two different whole numbers greater than 1. Their sum is no greater than 100, and Y is greater than X. S and P are two mathematicians (and consequently perfect logicians); S knows the sum X+Y and P knows the product X*Y. Both S and P know all the information in this paragraph. The following conversation occurs: S says "P does not know X and Y." P says "Now I know X and Y." S says "Now I also know X and Y!" What are X and Y? Guidance It can be hard to wrap one's head around what the three lines of dialog between S (the "sum guy") and P (the "product guy") convey about the values of X and Y. So for your convenience, here's a break-down: Quote Implied fact 1) S says "P does not know X and Y." For every possible sum decomposition of the number X+Y, the product has in turn more than one product decomposition. 2) P says "Now I know X and Y." The number X*Y has only one product decomposition for which fact 1 is true. 3) S says "Now I also know X and Y." The number X+Y has only one sum decomposition for which fact 2 is true. Terminology: "sum decomposition" of a number = Any pair of positive integers (A, B) so that A+B equals the number. Here, with the additional constraint 2 ≤ A < B. "product decomposition" of a number = Any pair of positive integers (A, B) so that A*B equals the number. Here, with the additional constraint 2 ≤ A < B. Your program can solve the puzzle by considering all possible pairs (X, Y) in the range 2 ≤ X < Y ≤ 98, and then successively eliminating candidates based on the three facts. It turns out only one solution remains! See the Python example for an implementation that uses this approach with a few optimizations. See also   Wikipedia:   Sum and Product Puzzle
#Scheme
Scheme
  (import (scheme base) (scheme cxr) (scheme write) (srfi 1))   ;; utility method to find unique sum/product in given list (define (unique-items lst key) (let ((all-items (map key lst))) (filter (lambda (i) (= 1 (count (lambda (p) (= p (key i))) all-items))) lst)))   ;; list of all (x y x+y x*y) combinations with y > x (define *xy-pairs* (apply append (map (lambda (i) (map (lambda (j) (list i j (+ i j) (* i j))) (iota (- 98 i) (+ 1 i)))) (iota 96 2))))   ;; S says "P does not know X and Y" (define *products* ; get products which have multiple decompositions (let ((all-products (map fourth *xy-pairs*))) (filter (lambda (p) (> (count (lambda (i) (= i p)) all-products) 1)) all-products)))   (define *fact-1* ; every x+y has x*y in *products* (filter (lambda (i) (every (lambda (p) (memq (fourth p) *products*)) (filter (lambda (p) (= (third i) (third p))) *xy-pairs*))) *xy-pairs*))   ;; P says "Now I know X and Y" (define *fact-2* ; find the unique X*Y (unique-items *fact-1* fourth))   ;; S says "Now I also know X and Y" (define *fact-3* ; find the unique X+Y (unique-items *fact-2* third))   (display (string-append "Initial pairs: " (number->string (length *xy-pairs*)) "\n")) (display (string-append "After S: " (number->string (length *fact-1*)) "\n")) (display (string-append "After P: " (number->string (length *fact-2*)) "\n")) (display (string-append "After S: " (number->string (length *fact-3*)) "\n")) (display (string-append "X: " (number->string (caar *fact-3*)) " Y: " (number->string (cadar *fact-3*)) "\n"))  
http://rosettacode.org/wiki/Sum_of_a_series
Sum of a series
Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k = 1 n 1 k 2 {\displaystyle S_{n}=\sum _{k=1}^{n}{\frac {1}{k^{2}}}} and compute   S 1000 {\displaystyle S_{1000}} This approximates the   zeta function   for   S=2,   whose exact value ζ ( 2 ) = π 2 6 {\displaystyle \zeta (2)={\pi ^{2} \over 6}} is the solution of the Basel problem.
#BASIC
BASIC
FUNCTION s(x%) s = 1 / x ^ 2 END FUNCTION   FUNCTION sum(low%, high%) ret = 0 FOR i = low TO high ret = ret + s(i) NEXT i sum = ret END FUNCTION PRINT sum(1, 1000)
http://rosettacode.org/wiki/System_time
System time
Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related task   Date format See also   Retrieving system time (wiki)
#Yabasic
Yabasic
print time$
http://rosettacode.org/wiki/System_time
System time
Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related task   Date format See also   Retrieving system time (wiki)
#zkl
zkl
Time.Clock.time //-->seconds since the epoch (C/OS defined)
http://rosettacode.org/wiki/Sum_to_100
Sum to 100
Task Find solutions to the   sum to one hundred   puzzle. Add (insert) the mathematical operators     +   or   -     (plus or minus)   before any of the digits in the decimal numeric string   123456789   such that the resulting mathematical expression adds up to a particular sum   (in this iconic case,   100). Example: 123 + 4 - 5 + 67 - 89 = 100 Show all output here.   Show all solutions that sum to   100   Show the sum that has the maximum   number   of solutions   (from zero to infinity‡)   Show the lowest positive sum that   can't   be expressed   (has no solutions),   using the rules for this task   Show the ten highest numbers that can be expressed using the rules for this task   (extra credit) ‡   (where   infinity   would be a relatively small   123,456,789) An example of a sum that can't be expressed   (within the rules of this task)   is:   5074 (which,   of course,   isn't the lowest positive sum that can't be expressed).
#AWK
AWK
# # RossetaCode: Sum to 100, AWK. # # Find solutions to the "sum to one hundred" puzzle.   function evaluate(code) { value = 0 number = 0 power = 1 for ( k = 9; k >= 1; k-- ) { number = power*k + number op = code % 3 if ( op == 0 ) { value = value + number number = 0 power = 1 } else if (op == 1 ) { value = value - number number = 0 power = 1 } else if ( op == 2) { power = power * 10 } else { } code = int(code / 3); } return value; }   function show(code) { s = "" a = 19683 b = 6561   for ( k = 1; k <= 9; k++ ) { op = int( (code % a) / b ) if ( op == 0 && k > 1 ) s = s "+" else if ( op == 1 ) s = s "-" else { } a = b b = int(b / 3) s = s k } printf "%9d = %s\n", evaluate(code), s; }     BEGIN { nexpr = 13122   print print "Show all solutions that sum to 100" print for ( i = 0; i < nexpr; i++ ) if ( evaluate(i) == 100 ) show(i);   print print "Show the sum that has the maximum number of solutions" print for ( i = 0; i < nexpr; i++ ) { sum = evaluate(i); if ( sum >= 0 ) stat[sum]++; } best = (-1); for ( sum in stat ) if ( best < stat[sum] ) { best = stat[sum] bestSum = sum } delete stat printf "%d has %d solutions\n", bestSum, best   print print "Show the lowest positive number that can't be expressed" print for ( i = 0; i <= 123456789; i++ ){ for ( j = 0; j < nexpr; j++ ) if ( i == evaluate(j) ) break; if ( i != evaluate(j) ) break; } printf "%d\n",i   print print "Show the ten highest numbers that can be expressed" print limit = 123456789 + 1; for ( i = 1; i <= 10; i++ ) { best = 0; for ( j = 0; j < nexpr; j++ ) { test = evaluate(j); if ( test < limit && test > best ) best = test; } for ( j = 0; j < nexpr; j++ ) if ( evaluate(j) == best ) show(j) limit = best } }
http://rosettacode.org/wiki/Sum_multiples_of_3_and_5
Sum multiples of 3 and 5
Task The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n. Show output for n = 1000. This is is the same as Project Euler problem 1. Extra credit: do this efficiently for n = 1e20 or higher.
#BCPL
BCPL
  GET "libhdr"   LET sumdiv(n, d) = VALOF { LET m = n/d RESULTIS m*(m + 1)/2 * d }   LET sum3or5(n) = sumdiv(n, 3) + sumdiv(n, 5) - sumdiv(n, 15)   LET start() = VALOF { LET sum = 0 LET n = 1   FOR k = 1 TO 999 DO IF k MOD 3 = 0 | k MOD 5 = 0 THEN sum +:= k writef("The sum of the multiples of 3 and 5 < 1000 is %d *n", sum)   writef("Next, the awesome power of inclusion/exclusion...*n"); FOR i = 1 TO 10 { writef("%11d %d *n", n, sum3or5(n - 1)) n *:= 10 }   RESULTIS 0 }  
http://rosettacode.org/wiki/Sum_digits_of_an_integer
Sum digits of an integer
Task Take a   Natural Number   in a given base and return the sum of its digits:   110         sums to   1   123410   sums to   10   fe16       sums to   29   f0e16     sums to   29
#BBC_BASIC
BBC BASIC
*FLOAT64 PRINT "Digit sum of 1 (base 10) is "; FNdigitsum(1, 10) PRINT "Digit sum of 12345 (base 10) is "; FNdigitsum(12345, 10) PRINT "Digit sum of 9876543210 (base 10) is "; FNdigitsum(9876543210, 10) PRINT "Digit sum of FE (base 16) is "; ~FNdigitsum(&FE, 16) " (base 16)" PRINT "Digit sum of F0E (base 16) is "; ~FNdigitsum(&F0E, 16) " (base 16)" END   DEF FNdigitsum(n, b) LOCAL q, s WHILE n <> 0 q = INT(n / b) s += n - q * b n = q ENDWHILE = s
http://rosettacode.org/wiki/Sum_of_squares
Sum of squares
Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
#BQN
BQN
SSq ← +´√⁼   •Show SSq 1‿2‿3‿4‿5 •Show SSq ⟨⟩
http://rosettacode.org/wiki/Sum_of_squares
Sum of squares
Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
#Bracmat
Bracmat
( ( sumOfSquares = sum component . 0:?sum & whl ' ( !arg:%?component ?arg & !component^2+!sum:?sum ) & !sum ) & out$(sumOfSquares$(3 4)) & out$(sumOfSquares$(3 4 i*5)) & out$(sumOfSquares$(a b c)) );
http://rosettacode.org/wiki/Sum_and_product_of_an_array
Sum and product of an array
Task Compute the sum and product of an array of integers.
#Arturo
Arturo
arr: 1..10   print ["Sum =" sum arr] print ["Product =" product arr]
http://rosettacode.org/wiki/Sum_and_product_of_an_array
Sum and product of an array
Task Compute the sum and product of an array of integers.
#Asymptote
Asymptote
int[] matriz = {1,2,3,4,5}; int suma = 0, prod = 1;   for (int p : matriz) { suma += p; prod *= p; } write("Sum = ", suma); write("Product = ", prod);
http://rosettacode.org/wiki/Sum_and_product_puzzle
Sum and product puzzle
Task[edit] Solve the "Impossible Puzzle": X and Y are two different whole numbers greater than 1. Their sum is no greater than 100, and Y is greater than X. S and P are two mathematicians (and consequently perfect logicians); S knows the sum X+Y and P knows the product X*Y. Both S and P know all the information in this paragraph. The following conversation occurs: S says "P does not know X and Y." P says "Now I know X and Y." S says "Now I also know X and Y!" What are X and Y? Guidance It can be hard to wrap one's head around what the three lines of dialog between S (the "sum guy") and P (the "product guy") convey about the values of X and Y. So for your convenience, here's a break-down: Quote Implied fact 1) S says "P does not know X and Y." For every possible sum decomposition of the number X+Y, the product has in turn more than one product decomposition. 2) P says "Now I know X and Y." The number X*Y has only one product decomposition for which fact 1 is true. 3) S says "Now I also know X and Y." The number X+Y has only one sum decomposition for which fact 2 is true. Terminology: "sum decomposition" of a number = Any pair of positive integers (A, B) so that A+B equals the number. Here, with the additional constraint 2 ≤ A < B. "product decomposition" of a number = Any pair of positive integers (A, B) so that A*B equals the number. Here, with the additional constraint 2 ≤ A < B. Your program can solve the puzzle by considering all possible pairs (X, Y) in the range 2 ≤ X < Y ≤ 98, and then successively eliminating candidates based on the three facts. It turns out only one solution remains! See the Python example for an implementation that uses this approach with a few optimizations. See also   Wikipedia:   Sum and Product Puzzle
#Sidef
Sidef
func grep_uniq(a, by) { a.group_by{ .(by) }.values.grep{.len == 1}.map{_[0]} } func sums (n) { 2 .. n//2 -> map {|i| [i, n-i] } }   var pairs = (2..97 -> map {|i| ([i] ~X (i+1 .. 98))... })   var p_uniq = Hash() p_uniq{grep_uniq(pairs, :prod).map { .to_s }...} = ()   var s_pairs = pairs.grep {|p| sums(p.sum).all { !p_uniq.contains(.to_s) } } var p_pairs = grep_uniq(s_pairs, :prod) var f_pairs = grep_uniq(p_pairs, :sum)   f_pairs.each { |p| printf("X = %d, Y = %d\n", p...) }
http://rosettacode.org/wiki/Sum_of_a_series
Sum of a series
Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k = 1 n 1 k 2 {\displaystyle S_{n}=\sum _{k=1}^{n}{\frac {1}{k^{2}}}} and compute   S 1000 {\displaystyle S_{1000}} This approximates the   zeta function   for   S=2,   whose exact value ζ ( 2 ) = π 2 6 {\displaystyle \zeta (2)={\pi ^{2} \over 6}} is the solution of the Basel problem.
#bc
bc
define f(x) { return(1 / (x * x)) }   define s(n) { auto i, s   for (i = 1; i <= n; i++) { s += f(i) }   return(s) }   scale = 20 s(1000)
http://rosettacode.org/wiki/Sum_to_100
Sum to 100
Task Find solutions to the   sum to one hundred   puzzle. Add (insert) the mathematical operators     +   or   -     (plus or minus)   before any of the digits in the decimal numeric string   123456789   such that the resulting mathematical expression adds up to a particular sum   (in this iconic case,   100). Example: 123 + 4 - 5 + 67 - 89 = 100 Show all output here.   Show all solutions that sum to   100   Show the sum that has the maximum   number   of solutions   (from zero to infinity‡)   Show the lowest positive sum that   can't   be expressed   (has no solutions),   using the rules for this task   Show the ten highest numbers that can be expressed using the rules for this task   (extra credit) ‡   (where   infinity   would be a relatively small   123,456,789) An example of a sum that can't be expressed   (within the rules of this task)   is:   5074 (which,   of course,   isn't the lowest positive sum that can't be expressed).
#C
C
/* * RossetaCode: Sum to 100, C99, an algorithm using ternary numbers. * * Find solutions to the "sum to one hundred" puzzle. */   #include <stdio.h> #include <stdlib.h>   /* * There are only 13122 (i.e. 2*3**8) different possible expressions, * thus we can encode them as positive integer numbers from 0 to 13121. */ #define NUMBER_OF_EXPRESSIONS (2 * 3*3*3*3 * 3*3*3*3 ) enum OP { ADD, SUB, JOIN }; typedef int (*cmp)(const void*, const void*);   // Replacing struct Expression and struct CountSum by a tuple like // struct Pair { int first; int last; } is possible but would make the source // code less readable.   struct Expression{ int sum; int code; }expressions[NUMBER_OF_EXPRESSIONS]; int expressionsLength = 0; int compareExpressionBySum(const struct Expression* a, const struct Expression* b){ return a->sum - b->sum; }   struct CountSum{ int counts; int sum; }countSums[NUMBER_OF_EXPRESSIONS]; int countSumsLength = 0; int compareCountSumsByCount(const struct CountSum* a, const struct CountSum* b){ return a->counts - b->counts; }   int evaluate(int code){ int value = 0, number = 0, power = 1; for ( int k = 9; k >= 1; k-- ){ number = power*k + number; switch( code % 3 ){ case ADD: value = value + number; number = 0; power = 1; break; case SUB: value = value - number; number = 0; power = 1; break; case JOIN: power = power * 10 ; break; } code /= 3; } return value; }   void print(int code){ static char s[19]; char* p = s; int a = 19683, b = 6561; for ( int k = 1; k <= 9; k++ ){ switch((code % a) / b){ case ADD: if ( k > 1 ) *p++ = '+'; break; case SUB: *p++ = '-'; break; } a = b; b = b / 3; *p++ = '0' + k; } *p = 0; printf("%9d = %s\n", evaluate(code), s); }   void comment(char* string){ printf("\n\n%s\n\n", string); }   void init(void){ for ( int i = 0; i < NUMBER_OF_EXPRESSIONS; i++ ){ expressions[i].sum = evaluate(i); expressions[i].code = i; } expressionsLength = NUMBER_OF_EXPRESSIONS; qsort(expressions,expressionsLength,sizeof(struct Expression),(cmp)compareExpressionBySum);   int j = 0; countSums[0].counts = 1; countSums[0].sum = expressions[0].sum; for ( int i = 0; i < expressionsLength; i++ ){ if ( countSums[j].sum != expressions[i].sum ){ j++; countSums[j].counts = 1; countSums[j].sum = expressions[i].sum; } else countSums[j].counts++; } countSumsLength = j + 1; qsort(countSums,countSumsLength,sizeof(struct CountSum),(cmp)compareCountSumsByCount); }   int main(void){   init();   comment("Show all solutions that sum to 100"); const int givenSum = 100; struct Expression ex = { givenSum, 0 }; struct Expression* found; if ( found = bsearch(&ex,expressions,expressionsLength, sizeof(struct Expression),(cmp)compareExpressionBySum) ){ while ( found != expressions && (found-1)->sum == givenSum ) found--; while ( found != &expressions[expressionsLength] && found->sum == givenSum ) print(found++->code); }   comment("Show the positve sum that has the maximum number of solutions"); int maxSumIndex = countSumsLength - 1; while( countSums[maxSumIndex].sum < 0 ) maxSumIndex--; printf("%d has %d solutions\n", countSums[maxSumIndex].sum, countSums[maxSumIndex].counts);   comment("Show the lowest positive number that can't be expressed"); for ( int value = 0; ; value++ ){ struct Expression ex = { value, 0 }; if (!bsearch(&ex,expressions,expressionsLength, sizeof(struct Expression),(cmp)compareExpressionBySum)){ printf("%d\n", value); break; } }   comment("Show the ten highest numbers that can be expressed"); for ( int i = expressionsLength-1; i >= expressionsLength-10; i-- ) print(expressions[i].code);   return 0; }
http://rosettacode.org/wiki/Sum_multiples_of_3_and_5
Sum multiples of 3 and 5
Task The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n. Show output for n = 1000. This is is the same as Project Euler problem 1. Extra credit: do this efficiently for n = 1e20 or higher.
#Befunge
Befunge
&1-:!#v_:3%#v_ >:># >+\:v >:5%#v_^ @.$_^#! < > ^
http://rosettacode.org/wiki/Sum_digits_of_an_integer
Sum digits of an integer
Task Take a   Natural Number   in a given base and return the sum of its digits:   110         sums to   1   123410   sums to   10   fe16       sums to   29   f0e16     sums to   29
#bc
bc
define s(n) { auto i, o, s   o = scale scale = 0   for (i = n; i > 0; i /= ibase) { s += i % ibase }   scale = o return(s) }   ibase = 10 s(1) s(1234) ibase = 16 s(FE) s(F0E)
http://rosettacode.org/wiki/Sum_of_squares
Sum of squares
Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
#Brat
Brat
p 1.to(10).reduce 0 { res, n | res = res + n ^ 2 } #Prints 385
http://rosettacode.org/wiki/Sum_of_squares
Sum of squares
Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
#C
C
#include <stdio.h>   double squaredsum(double *l, int e) { int i; double sum = 0.0; for(i = 0 ; i < e ; i++) sum += l[i]*l[i]; return sum; }   int main() { double list[6] = {3.0, 1.0, 4.0, 1.0, 5.0, 9.0};   printf("%lf\n", squaredsum(list, 6)); printf("%lf\n", squaredsum(list, 0)); /* the same without using a real list as if it were 0-element long */ printf("%lf\n", squaredsum(NULL, 0)); return 0; }
http://rosettacode.org/wiki/Sum_and_product_of_an_array
Sum and product of an array
Task Compute the sum and product of an array of integers.
#AutoHotkey
AutoHotkey
numbers = 1,2,3,4,5 product := 1 loop, parse, numbers, `, { sum += A_LoopField product *= A_LoopField } msgbox, sum = %sum%`nproduct = %product%
http://rosettacode.org/wiki/Sum_and_product_puzzle
Sum and product puzzle
Task[edit] Solve the "Impossible Puzzle": X and Y are two different whole numbers greater than 1. Their sum is no greater than 100, and Y is greater than X. S and P are two mathematicians (and consequently perfect logicians); S knows the sum X+Y and P knows the product X*Y. Both S and P know all the information in this paragraph. The following conversation occurs: S says "P does not know X and Y." P says "Now I know X and Y." S says "Now I also know X and Y!" What are X and Y? Guidance It can be hard to wrap one's head around what the three lines of dialog between S (the "sum guy") and P (the "product guy") convey about the values of X and Y. So for your convenience, here's a break-down: Quote Implied fact 1) S says "P does not know X and Y." For every possible sum decomposition of the number X+Y, the product has in turn more than one product decomposition. 2) P says "Now I know X and Y." The number X*Y has only one product decomposition for which fact 1 is true. 3) S says "Now I also know X and Y." The number X+Y has only one sum decomposition for which fact 2 is true. Terminology: "sum decomposition" of a number = Any pair of positive integers (A, B) so that A+B equals the number. Here, with the additional constraint 2 ≤ A < B. "product decomposition" of a number = Any pair of positive integers (A, B) so that A*B equals the number. Here, with the additional constraint 2 ≤ A < B. Your program can solve the puzzle by considering all possible pairs (X, Y) in the range 2 ≤ X < Y ≤ 98, and then successively eliminating candidates based on the three facts. It turns out only one solution remains! See the Python example for an implementation that uses this approach with a few optimizations. See also   Wikipedia:   Sum and Product Puzzle
#Wren
Wren
import "/dynamic" for Tuple import "/seq" for Lst   var P = Tuple.create("P", ["x", "y", "sum", "prod"])   var intersect = Fn.new { |l1, l2| var l3 = (l1.count < l2.count) ? l1 : l2 var l4 = (l3 == l1) ? l2 : l1 var l5 = [] for (e in l3) if (l4.contains(e)) l5.add(e) return l5 }   var candidates = [] for (x in 2..49) { for (y in x + 1..100 - x) { candidates.add(P.new(x, y, x + y, x * y)) } }   var sumGroups = Lst.groups(candidates) { |c| c.sum } var prodGroups = Lst.groups(candidates) { |c| c.prod } var sumMap = {} for (sumGroup in sumGroups) { sumMap[sumGroup[0]] = sumGroup[1].map { |l| l[0] }.toList } var prodMap = {} for (prodGroup in prodGroups) { prodMap[prodGroup[0]] = prodGroup[1].map { |l| l[0] }.toList } var fact1 = candidates.where { |c| sumMap[c.sum].all { |c| prodMap[c.prod].count > 1 } }.toList var fact2 = fact1.where { |c| intersect.call(prodMap[c.prod], fact1).count == 1 }.toList var fact3 = fact2.where { |c| intersect.call(sumMap[c.sum], fact2).count == 1 }.toList System.write("The only solution is : ") for (p in fact3) System.print("x = %(p.x), y = %(p.y)")
http://rosettacode.org/wiki/Sum_of_a_series
Sum of a series
Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k = 1 n 1 k 2 {\displaystyle S_{n}=\sum _{k=1}^{n}{\frac {1}{k^{2}}}} and compute   S 1000 {\displaystyle S_{1000}} This approximates the   zeta function   for   S=2,   whose exact value ζ ( 2 ) = π 2 6 {\displaystyle \zeta (2)={\pi ^{2} \over 6}} is the solution of the Basel problem.
#Beads
Beads
beads 1 program 'Sum of a series' calc main_init var k = 0 loop reps:1000 count:n k = k + 1/n^2 log to_str(k)
http://rosettacode.org/wiki/Sum_to_100
Sum to 100
Task Find solutions to the   sum to one hundred   puzzle. Add (insert) the mathematical operators     +   or   -     (plus or minus)   before any of the digits in the decimal numeric string   123456789   such that the resulting mathematical expression adds up to a particular sum   (in this iconic case,   100). Example: 123 + 4 - 5 + 67 - 89 = 100 Show all output here.   Show all solutions that sum to   100   Show the sum that has the maximum   number   of solutions   (from zero to infinity‡)   Show the lowest positive sum that   can't   be expressed   (has no solutions),   using the rules for this task   Show the ten highest numbers that can be expressed using the rules for this task   (extra credit) ‡   (where   infinity   would be a relatively small   123,456,789) An example of a sum that can't be expressed   (within the rules of this task)   is:   5074 (which,   of course,   isn't the lowest positive sum that can't be expressed).
#C.23
C#
using System; using System.Collections.Generic; using System.Linq;   class Program { static void Main(string[] args) { // All unique expressions that have a plus sign in front of the 1; calculated in parallel var expressionsPlus = Enumerable.Range(0, (int)Math.Pow(3, 8)).AsParallel().Select(i => new Expression(i, 1)); // All unique expressions that have a minus sign in front of the 1; calculated in parallel var expressionsMinus = Enumerable.Range(0, (int)Math.Pow(3, 8)).AsParallel().Select(i => new Expression(i, -1)); var expressions = expressionsPlus.Concat(expressionsMinus); var results = new Dictionary<int, List<Expression>>(); foreach (var e in expressions) { if (results.Keys.Contains(e.Value)) results[e.Value].Add(e); else results[e.Value] = new List<Expression>() { e }; } Console.WriteLine("Show all solutions that sum to 100"); foreach (Expression e in results[100]) Console.WriteLine(" " + e); Console.WriteLine("Show the sum that has the maximum number of solutions (from zero to infinity)"); var summary = results.Keys.Select(k => new Tuple<int, int>(k, results[k].Count)); var maxSols = summary.Aggregate((a, b) => a.Item2 > b.Item2 ? a : b); Console.WriteLine(" The sum " + maxSols.Item1 + " has " + maxSols.Item2 + " solutions."); Console.WriteLine("Show the lowest positive sum that can't be expressed (has no solutions), using the rules for this task"); var lowestPositive = Enumerable.Range(1, int.MaxValue).First(x => !results.Keys.Contains(x)); Console.WriteLine(" " + lowestPositive); Console.WriteLine("Show the ten highest numbers that can be expressed using the rules for this task (extra credit)"); var highest = from k in results.Keys orderby k descending select k; foreach (var x in highest.Take(10)) Console.WriteLine(" " + x); } } public enum Operations { Plus, Minus, Join }; public class Expression { protected Operations[] Gaps; // 123456789 => there are 8 "gaps" between each number /// with 3 possibilities for each gap: plus, minus, or join public int Value; // What this expression sums up to protected int _one;   public Expression(int serial, int one) { _one = one; Gaps = new Operations[8]; // This represents "serial" as a base 3 number, each Gap expression being a base-three digit int divisor = 2187; // == Math.Pow(3,7) int times; for (int i = 0; i < 8; i++) { times = Math.DivRem(serial, divisor, out serial); divisor /= 3; if (times == 0) Gaps[i] = Operations.Join; else if (times == 1) Gaps[i] = Operations.Minus; else Gaps[i] = Operations.Plus; } // go ahead and calculate the value of this expression // because this is going to be done in a parallel thread (save time) Value = Evaluate(); } public override string ToString() { string ret = _one.ToString(); for (int i = 0; i < 8; i++) { switch (Gaps[i]) { case Operations.Plus: ret += "+"; break; case Operations.Minus: ret += "-"; break; } ret += (i + 2); } return ret; } private int Evaluate() /* Calculate what this expression equals */ { var numbers = new int[9]; int nc = 0; var operations = new List<Operations>(); int a = 1; for (int i = 0; i < 8; i++) { if (Gaps[i] == Operations.Join) a = a * 10 + (i + 2); else { if (a > 0) { if (nc == 0) a *= _one; numbers[nc++] = a; a = i + 2; } operations.Add(Gaps[i]); } } if (nc == 0) a *= _one; numbers[nc++] = a; int ni = 0; int left = numbers[ni++]; foreach (var operation in operations) { int right = numbers[ni++]; if (operation == Operations.Plus) left = left + right; else left = left - right; } return left; } }
http://rosettacode.org/wiki/Sum_multiples_of_3_and_5
Sum multiples of 3 and 5
Task The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n. Show output for n = 1000. This is is the same as Project Euler problem 1. Extra credit: do this efficiently for n = 1e20 or higher.
#BQN
BQN
Sum ← +´·(0=3⊸|⌊5⊸|)⊸/↕
http://rosettacode.org/wiki/Sum_digits_of_an_integer
Sum digits of an integer
Task Take a   Natural Number   in a given base and return the sum of its digits:   110         sums to   1   123410   sums to   10   fe16       sums to   29   f0e16     sums to   29
#BCPL
BCPL
get "libhdr"   let digitsum(n, base) = n=0 -> 0, n rem base + digitsum(n/base, base)   let start() be $( writef("%N*N", digitsum(1, 10)) // prints 1 writef("%N*N", digitsum(1234, 10)) // prints 10 writef("%N*N", digitsum(#1234, 8)) // also prints 10 writef("%N*N", digitsum(#XFE, 16)) // prints 29 writef("%N*N", digitsum(#XF0E, 16)) // also prints 29 $)
http://rosettacode.org/wiki/Sum_of_squares
Sum of squares
Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
#C.23
C#
using System; using System.Collections.Generic; using System.Linq;   class Program { static int SumOfSquares(IEnumerable<int> list) { return list.Sum(x => x * x); } static void Main(string[] args) { Console.WriteLine(SumOfSquares(new int[] { 4, 8, 15, 16, 23, 42 })); // 2854 Console.WriteLine(SumOfSquares(new int[] { 1, 2, 3, 4, 5 })); // 55 Console.WriteLine(SumOfSquares(new int[] { })); // 0 } }
http://rosettacode.org/wiki/Substitution_cipher
Substitution cipher
Substitution Cipher Implementation - File Encryption/Decryption Task Encrypt a input/source file by replacing every upper/lower case alphabets of the source file with another predetermined upper/lower case alphabets or symbols and save it into another output/encrypted file and then again convert that output/encrypted file into original/decrypted file. This type of Encryption/Decryption scheme is often called a Substitution Cipher. Related tasks Caesar cipher Rot-13 Vigenère Cipher/Cryptanalysis See also Wikipedia: Substitution cipher
#11l
11l
V key = ‘]kYV}(!7P$n5_0i R:?jOWtF/=-pe'AD&@r6%ZXs"v*N[#wSl9zq2^+g;LoB`aGh{3.HIu4fbK)mU8|dMET><,Qc\C1yxJ’   F encode(s) V r = ‘’ L(c) s r ‘’= :key[c.code - 32] R r   F decode(s) V r = ‘’ L(c) s r ‘’= Char(code' :key.index(c) + 32) R r   V s = ‘The quick brown fox jumps over the lazy dog, who barks VERY loudly!’ V enc = encode(s) print(‘Encoded: ’enc) print(‘Decoded: ’decode(enc))
http://rosettacode.org/wiki/Sum_and_product_of_an_array
Sum and product of an array
Task Compute the sum and product of an array of integers.
#AWK
AWK
$ awk 'func sum(s){split(s,a);r=0;for(i in a)r+=a[i];return r}{print sum($0)}' 1 2 3 4 5 6 7 8 9 10 55   $ awk 'func prod(s){split(s,a);r=1;for(i in a)r*=a[i];return r}{print prod($0)}' 1 2 3 4 5 6 7 8 9 10 3628800
http://rosettacode.org/wiki/Sum_and_product_puzzle
Sum and product puzzle
Task[edit] Solve the "Impossible Puzzle": X and Y are two different whole numbers greater than 1. Their sum is no greater than 100, and Y is greater than X. S and P are two mathematicians (and consequently perfect logicians); S knows the sum X+Y and P knows the product X*Y. Both S and P know all the information in this paragraph. The following conversation occurs: S says "P does not know X and Y." P says "Now I know X and Y." S says "Now I also know X and Y!" What are X and Y? Guidance It can be hard to wrap one's head around what the three lines of dialog between S (the "sum guy") and P (the "product guy") convey about the values of X and Y. So for your convenience, here's a break-down: Quote Implied fact 1) S says "P does not know X and Y." For every possible sum decomposition of the number X+Y, the product has in turn more than one product decomposition. 2) P says "Now I know X and Y." The number X*Y has only one product decomposition for which fact 1 is true. 3) S says "Now I also know X and Y." The number X+Y has only one sum decomposition for which fact 2 is true. Terminology: "sum decomposition" of a number = Any pair of positive integers (A, B) so that A+B equals the number. Here, with the additional constraint 2 ≤ A < B. "product decomposition" of a number = Any pair of positive integers (A, B) so that A*B equals the number. Here, with the additional constraint 2 ≤ A < B. Your program can solve the puzzle by considering all possible pairs (X, Y) in the range 2 ≤ X < Y ≤ 98, and then successively eliminating candidates based on the three facts. It turns out only one solution remains! See the Python example for an implementation that uses this approach with a few optimizations. See also   Wikipedia:   Sum and Product Puzzle
#zkl
zkl
mul:=Utils.Helpers.summer.fp1('*,1); //-->list.reduce('*,1), multiply list items var allPairs=[[(a,b); [2..100]; { [a+1..100] },{ a+b<100 }; ROList]]; // 2,304 pairs   sxys,pxys:=Dictionary(),Dictionary(); // hashes of allPairs sums and products: 95,1155 foreach xy in (allPairs){ sxys.appendV(xy.sum(),xy); pxys.appendV(xy:mul(_),xy) }   sOK:= 'wrap(s){ (not sxys[s].filter1('wrap(xy){ pxys[xy:mul(_)].len()<2 })) }; pOK:= 'wrap(p){ 1==pxys[p].filter('wrap([(x,y)]){ sOK(x+y) }).len() }; sOK2:='wrap(s){ 1==sxys[s].filter('wrap(xy){ pOK(xy:mul(_)) }).len() }; allPairs.filter('wrap([(x,y)]){ sOK(x+y) and pOK(x*y) and sOK2(x+y) }) .println();
http://rosettacode.org/wiki/Sum_of_a_series
Sum of a series
Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k = 1 n 1 k 2 {\displaystyle S_{n}=\sum _{k=1}^{n}{\frac {1}{k^{2}}}} and compute   S 1000 {\displaystyle S_{1000}} This approximates the   zeta function   for   S=2,   whose exact value ζ ( 2 ) = π 2 6 {\displaystyle \zeta (2)={\pi ^{2} \over 6}} is the solution of the Basel problem.
#Befunge
Befunge
05558***>::"~"%00p"~"/10p"( }}2"*v v*8555$_^#!:-1+*"~"g01g00+/*:\***< <@$_,#!>#:<+*<v+*86%+55:p00<6\0/** "."\55+%68^>\55+/00g1-:#^_$
http://rosettacode.org/wiki/Sum_to_100
Sum to 100
Task Find solutions to the   sum to one hundred   puzzle. Add (insert) the mathematical operators     +   or   -     (plus or minus)   before any of the digits in the decimal numeric string   123456789   such that the resulting mathematical expression adds up to a particular sum   (in this iconic case,   100). Example: 123 + 4 - 5 + 67 - 89 = 100 Show all output here.   Show all solutions that sum to   100   Show the sum that has the maximum   number   of solutions   (from zero to infinity‡)   Show the lowest positive sum that   can't   be expressed   (has no solutions),   using the rules for this task   Show the ten highest numbers that can be expressed using the rules for this task   (extra credit) ‡   (where   infinity   would be a relatively small   123,456,789) An example of a sum that can't be expressed   (within the rules of this task)   is:   5074 (which,   of course,   isn't the lowest positive sum that can't be expressed).
#C.2B.2B
C++
/* * RossetaCode: Sum to 100, C++, STL, OOP. * Works with: MSC 16.0 (MSVS2010); GCC 5.1 (use -std=c++11 or -std=c++14 etc.). * * Find solutions to the "sum to one hundred" puzzle. */ #include <iostream> #include <iomanip> #include <algorithm> #include <string> #include <set> #include <map>   using namespace std;   class Expression{ private: enum { NUMBER_OF_DIGITS = 9 }; // hack for C++98, use const int in C++11 enum Op { ADD, SUB, JOIN }; int code[NUMBER_OF_DIGITS]; public: static const int NUMBER_OF_EXPRESSIONS; Expression(){ for ( int i = 0; i < NUMBER_OF_DIGITS; i++ ) code[i] = ADD; } Expression& operator++(int){ // post incrementation for ( int i = 0; i < NUMBER_OF_DIGITS; i++ ) if ( ++code[i] > JOIN ) code[i] = ADD; else break; return *this; } operator int() const{ int value = 0, number = 0, sign = (+1); for ( int digit = 1; digit <= 9; digit++ ) switch ( code[NUMBER_OF_DIGITS - digit] ){ case ADD: value += sign*number; number = digit; sign = (+1); break; case SUB: value += sign*number; number = digit; sign = (-1); break; case JOIN: number = 10*number + digit; break; } return value + sign*number; } operator string() const{ string s; for ( int digit = 1; digit <= NUMBER_OF_DIGITS; digit++ ){ switch( code[NUMBER_OF_DIGITS - digit] ){ case ADD: if ( digit > 1 ) s.push_back('+'); break; case SUB: s.push_back('-'); break; } s.push_back('0' + digit); } return s; } }; const int Expression::NUMBER_OF_EXPRESSIONS = 2 * 3*3*3*3 * 3*3*3*3;   ostream& operator<< (ostream& os, Expression& ex){ ios::fmtflags oldFlags(os.flags()); os << setw(9) << right << static_cast<int>(ex) << " = " << setw(0) << left << static_cast<string>(ex) << endl; os.flags(oldFlags); return os; }   struct Stat{ map<int,int> countSum; map<int, set<int> > sumCount; Stat(){ Expression expression; for ( int i = 0; i < Expression::NUMBER_OF_EXPRESSIONS; i++, expression++ ) countSum[expression]++; for ( auto it = countSum.begin(); it != countSum.end(); it++ ) sumCount[it->second].insert(it->first); } };   void print(int givenSum){ Expression expression; for ( int i = 0; i < Expression::NUMBER_OF_EXPRESSIONS; i++, expression++ ) if ( expression == givenSum ) cout << expression; }   void comment(string commentString){ cout << endl << commentString << endl << endl; }   int main(){ Stat stat;   comment( "Show all solutions that sum to 100" ); const int givenSum = 100; print(givenSum);   comment( "Show the sum that has the maximum number of solutions" ); auto maxi = max_element(stat.sumCount.begin(),stat.sumCount.end()); auto it = maxi->second.begin(); while ( *it < 0 ) it++; cout << static_cast<int>(*it) << " has " << maxi->first << " solutions" << endl;   comment( "Show the lowest positive number that can't be expressed" ); int value = 0; while(stat.countSum.count(value) != 0) value++; cout << value << endl;   comment( "Show the ten highest numbers that can be expressed" ); auto rit = stat.countSum.rbegin(); for ( int i = 0; i < 10; i++, rit++ ) print(rit->first);   return 0; }