lambdaway
::
harshad
6
|
list
|
login
|
load
|
|
_h1 harshad or niven | [[zuckerman|?view=zuckerman_numbers]] _p Following [[https://rosettacode.org/wiki/Harshad_or_Niven_series#JavaScript|https://rosettacode.org/wiki/Harshad_or_Niven_series#JavaScript]] the Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits. For example, 42 is a Harshad number as 42 is divisible by (4 + 2) without remainder. _p Task: Assume that the series is defined as the numbers in increasing order. The task is to create a function/method/procedure to generate successive members of the Harshad sequence. Use it to: _ul list the first 20 members of the sequence, and _ul list the first Harshad number greater than 1000. {prewrap '{def harshad? {def harshad?.sum {lambda {:n} {if {W.empty? {W.rest :n}} then {W.first :n} else {+ {W.first :n} {harshad?.sum {W.rest :n}}} }}} {lambda {:n} {= {% :n {harshad?.sum :n}} 0} }} -> {def harshad? {def harshad?.sum {lambda {:n} {if {W.empty? {W.rest :n}} then {W.first :n} else {+ {W.first :n} {harshad?.sum {W.rest :n}}} }}} {lambda {:n} {= {% :n {harshad?.sum :n}} 0} }} '{harshad? 12} -> {harshad? 12} '{harshad? 13} -> {harshad? 13} '{def harshads {def harshads.loop {lambda {:a :n :i} {if {> {A.length :a} :n} then :a else {harshads.loop {if {harshad? :i} then {A.addlast! :i :a} else :a} :n {+ :i 1}} }}} {lambda {:n} {harshads.loop {A.new} :n 0} }} -> {def harshads {def harshads.loop {lambda {:a :n :i} {if {> {A.length :a} :n} then :a else {harshads.loop {if {harshad? :i} then {A.addlast! :i :a} else :a} :n {+ :i 1}} }}} {lambda {:n} {harshads.loop {A.new} :n 0} }} '{harshads 20} -> {harshads 20} '{def firstharshadafter {def firstharshadafter.loop {lambda {:i} {if {harshad? :i} then :i else {firstharshadafter.loop {+ :i 1}} }}} {lambda {:n} {firstharshadafter.loop {+ :n 1}} }} -> {def firstharshadafter {def firstharshadafter.loop {lambda {:i} {if {harshad? :i} then :i else {firstharshadafter.loop {+ :i 1}}}}} {lambda {:n} {firstharshadafter.loop {+ :n 1}}}} '{firstharshadafter 1000} -> {firstharshadafter 1000} } {script function isHarshad(n) { var s = 0; var n_str = new String(n); for (var i = 0; i < n_str.length; ++i) { s += parseInt(n_str.charAt(i)); } return n % s === 0; } var count = 0; var harshads = []; for (var n = 1; count < 20; ++n) { if (isHarshad(n)) { count++; harshads.push(n); } } // alert(harshads.join(" ")); var h = 1000; while (!isHarshad(++h)); // alert(h); LAMBDATALK.DICT["isharshad"] = function() { return (isHarshad( Number( arguments[0].trim() )) )? "true" : "false" }; }
lambdaway v.20211111