Data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 7387c8f97b
commit cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions

View file

@ -0,0 +1,2 @@
---
from: http://rosettacode.org/wiki/Gapful_numbers

View file

@ -0,0 +1,38 @@
Numbers   (positive integers expressed in base ten)   that are (evenly) divisible by the number formed by the
first and last digit are known as   '''gapful numbers'''.
''Evenly divisible''   means divisible with   no   remainder.
All   one─   and two─digit   numbers have this property and are trivially excluded.   Only
numbers &nbsp; <big> &ge; </big> '''100''' &nbsp; will be considered for this Rosetta Code task.
;Example:
<big>'''187'''</big> &nbsp; is a &nbsp; '''gapful''' &nbsp; number because it is evenly divisible by the
number &nbsp; <big>'''17'''</big> &nbsp; which is formed by the first and last decimal digits
of &nbsp; <big> '''<u>1</u>8<u>7</u>'''. </big>
About &nbsp; <big>7.46%</big> &nbsp; of positive integers are &nbsp; ''gapful''.
;Task:
:* &nbsp; Generate and show all sets of numbers (below) on one line (horizontally) with a title, &nbsp; here on this page
:* &nbsp; Show the first &nbsp; '''30''' &nbsp; gapful numbers
:* &nbsp; Show the first &nbsp; '''15''' &nbsp; gapful numbers &nbsp; <big> &ge; </big> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;'''1,000,000'''
:* &nbsp; Show the first &nbsp; '''10''' &nbsp; gapful numbers &nbsp; <big> &ge; </big> &nbsp; '''1,000,000,000'''
;Related tasks:
:* &nbsp; [https://rosettacode.org/wiki/Harshad_or_Niven_series Harshad or Niven series].
:* &nbsp; [https://rosettacode.org/wiki/Palindromic_gapful_numbers palindromic gapful numbers].
:* &nbsp; [https://rosettacode.org/wiki/Largest_number_divisible_by_its_digits largest number divisible by its digits].
;Also see:
:* &nbsp; The OEIS entry: &nbsp; [https://oeis.org/A108343 A108343 gapful numbers].
:* &nbsp; numbersaplenty [http://www.numbersaplenty.com/set/gapful_number/ gapful numbers]
<br><br>

View file

@ -0,0 +1,9 @@
L(start, n) [(100, 30), (1'000'000, 15), (1'000'000'000, 10)]
print("\nFirst "n gapful numbers from start)
[Int] l
L(x) start..
I x % (Int(String(x)[0]) * 10 + (x % 10)) == 0
l.append(x)
I l.len == n
L.break
print(l)

View file

@ -0,0 +1,39 @@
BEGIN # find some gapful numbers - numbers divisible by f*10 + b #
# where f is the first digit and b is the final digit #
# unary GAPFUL operator - returns TRUE if n is gapful #
# FALSE otherwise #
OP GAPFUL = ( INT n )BOOL:
BEGIN
INT abs n = ABS n;
INT back = abs n MOD 10; # final digit #
INT front := abs n OVER 10;
WHILE front > 9 DO front OVERAB 10 OD;
abs n MOD ( ( front * 10 ) + back ) = 0
END; # GAPFUL #
# dyadic GAPFUL operator - returns an array of n gapful #
# numbers starting from first #
PRIO GAPFUL = 9;
OP GAPFUL = ( INT n, INT first )[]INT:
BEGIN
[ 1 : n ]INT result;
INT g pos := 0;
FOR i FROM first WHILE g pos < n DO
IF GAPFUL i THEN result[ g pos +:= 1 ] := i FI
OD;
result
END; # GAPFUL #
# prints a sequence of gapful numbers #
PROC print gapful = ( []INT seq, INT start )VOID:
BEGIN
print( ( "First ", whole( ( UPB seq + 1 ) - LWB seq, 0 )
, " gapful numbers starting from ", whole( start, 0 )
, ":", newline
)
);
FOR i FROM LWB seq TO UPB seq DO print( ( " ", whole( seq[ i ], 0 ) ) ) OD;
print( ( newline ) )
END; # print gapful #
print gapful( 30 GAPFUL 100, 100 );
print gapful( 15 GAPFUL 1 000 000, 1 000 000 );
print gapful( 10 GAPFUL 1 000 000 000, 1 000 000 000 )
END

View file

@ -0,0 +1,26 @@
# syntax: GAWK -f GAPFUL_NUMBERS.AWK
# converted from C++
BEGIN {
show_gapful(100,30)
show_gapful(1000000,15)
show_gapful(1000000000,10)
show_gapful(7123,25)
exit(0)
}
function is_gapful(n, m) {
m = n
while (m >= 10) {
m = int(m / 10)
}
return(n % ((n % 10) + 10 * (m % 10)) == 0)
}
function show_gapful(n, count,i) {
printf("first %d gapful numbers >= %d:",count,n)
for (i=0; i<count; n++) {
if (is_gapful(n)) {
printf(" %d",n)
i++
}
}
printf("\n")
}

View file

@ -0,0 +1,44 @@
with Ada.Text_IO; use Ada.Text_IO;
procedure Gapful_Numbers is
function Divisor (N : in Positive) return Positive is
NN : Positive := N;
begin
while NN >= 10 loop
NN := NN / 10;
end loop;
return 10 * NN + (N mod 10);
end Divisor;
function Is_Gapful (N : in Positive) return Boolean is
begin
return N mod Divisor (N) = 0;
end Is_Gapful;
procedure Find_Gapful (Count : in Positive; From : in Positive) is
Found : Natural := 0;
begin
for Candidate in From .. Positive'Last loop
if Is_Gapful (Candidate) then
Put (Candidate'Image);
Found := Found + 1;
exit when Found = Count;
end if;
end loop;
New_Line;
end Find_Gapful;
begin
Put_Line ("First 30 gapful numbers over 100:");
Find_Gapful (From => 100, Count => 30);
New_Line;
Put_Line ("First 15 gapful numbers over 1_000_000:");
Find_Gapful (From => 1_000_000, Count => 15);
New_Line;
Put_Line ("First 10 gapful numbers over 1_000_000_000:");
Find_Gapful (From => 1_000_000_000, Count => 10);
New_Line;
end Gapful_Numbers;

View file

@ -0,0 +1,31 @@
on isGapful(n)
set units to n mod 10
set temp to n div 10
repeat until (temp < 10)
set temp to temp div 10
end repeat
return (n mod (temp * 10 + units) = 0)
end isGapful
-- Task code:
on getGapfuls(n, q)
set collector to {}
repeat until ((count collector) = q)
if (isGapful(n)) then set end of collector to n
set n to n + 1
end repeat
return collector
end getGapfuls
local output, astid
set output to {}
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to " "
set end of output to "First 30 gapful numbers ≥ 100:" & linefeed & getGapfuls(100, 30)
set end of output to "First 15 gapful numbers ≥ 1,000,000:" & linefeed & getGapfuls(1000000, 15)
set end of output to "First 10 gapful numbers ≥ 100,000,000:" & linefeed & getGapfuls(1.0E+9, 10)
set AppleScript's text item delimiters to linefeed & linefeed
set output to output as text
set AppleScript's text item delimiters to astid
return output

View file

@ -0,0 +1,8 @@
"First 30 gapful numbers 100:
100 105 108 110 120 121 130 132 135 140 143 150 154 160 165 170 176 180 187 190 192 195 198 200 220 225 231 240 242 253
First 15 gapful numbers 1,000,000:
1000000 1000005 1000008 1000010 1000016 1000020 1000021 1000030 1000032 1000034 1000035 1000040 1000050 1000060 1000065
First 10 gapful numbers 1,000,000,000:
1.0E+9 1.000000001E+9 1.000000005E+9 1.000000008E+9 1.00000001E+9 1.000000016E+9 1.00000002E+9 1.000000027E+9 1.00000003E+9 1.000000032E+9"

View file

@ -0,0 +1,37 @@
100 START = 100
110 COUNT = 30
120 GOSUB 230"GENERATE GAPS"
130 PRINT
140 START = 1000000
150 COUNT = 15
160 GOSUB 230"GENERATE GAPS"
170 PRINT
180 START = 1000000000
190 COUNT = 15
200 GOSUB 230"GENERATE GAPS"
210 PRINT
220 END
230 GOSUB 340"PRINT START"
240 PRINT " :"M$
250 LET C = 0
260 FOR START = START TO 1E38
270 LET I$ = STR$ (START)
280 LET N = VAL ( LEFT$ (I$,1) + STR$ (START - INT (START / B) * B))
290 LET GAPFUL = START - INT (START / N) * N = 0
300 IF GAPFUL THEN GOSUB 370"PRINT GAPFUL"
310 IF C = COUNT THEN RETURN
320 NEXT START
330 STOP
340 LET M$ = CHR$ (13)
350 PRINT M$"FIRST "COUNT" ";
360 PRINT "GAPFUL NUMBERS >=";
370 LET C = C + 1
380 LET B = 10
390 LET P$ = ""
400 FOR P = START TO 0 STEP 0
410 LET Q = INT (P / B)
420 LET P$ = STR$ (P - Q * B) + P$
430 LET P = Q
440 NEXT P
450 PRINT MID$(M$ + " " + P$, 2 - (POS(0) + LEN(P$) + 1 > PEEK(33))) ;
460 RETURN

View file

@ -0,0 +1,24 @@
gapful?: function [n][
s: to :string n
divisor: to :integer (first s) ++ last s
0 = n % divisor
]
specs: [100 30, 1000000 15, 1000000000 10, 7123 25]
loop specs [start,count][
print "----------------------------------------------------------------"
print ["first" count "gapful numbers starting from" start]
print "----------------------------------------------------------------"
i: start
took: 0
while [took < count][
if gapful? i [
prints i
prints " "
took: took + 1
]
i: i + 1
]
print "\n"
]

View file

@ -0,0 +1,10 @@
Gapful_numbers(Min, Qty){
counter:= 0, output := ""
while (counter < Qty){
n := A_Index+Min-1
d := SubStr(n, 1, 1) * 10 + SubStr(n, 0)
if (n/d = Floor(n/d))
output .= ++counter ": " n "`t" n " / " d " = " Format("{:d}", n/d) "`n"
}
return output
}

View file

@ -0,0 +1,3 @@
MsgBox, 262144, , % Gapful_numbers(100, 30)
MsgBox, 262144, , % Gapful_numbers(1000000, 15)
MsgBox, 262144, , % Gapful_numbers(1000000000, 10)

View file

@ -0,0 +1,27 @@
function is_gapful(n)
m = n
l = n mod 10
while (m >= 10)
m = int(m / 10)
end while
return (m * 10) + l
end function
subroutine muestra_gapful(n, gaps)
inc = 0
print "Primeros "; gaps; " números gapful >= "; n
while inc < gaps
if n mod is_gapful(n) = 0 then
print " " ; n ;
inc = inc + 1
end if
n = n + 1
end while
print chr(10)
end subroutine
call muestra_gapful(100, 30)
call muestra_gapful(1000000, 15)
call muestra_gapful(1000000000, 10)
call muestra_gapful(7123,25)
end

View file

@ -0,0 +1,28 @@
#include <iostream>
bool gapful(int n) {
int m = n;
while (m >= 10)
m /= 10;
return n % ((n % 10) + 10 * (m % 10)) == 0;
}
void show_gapful_numbers(int n, int count) {
std::cout << "First " << count << " gapful numbers >= " << n << ":\n";
for (int i = 0; i < count; ++n) {
if (gapful(n)) {
if (i != 0)
std::cout << ", ";
std::cout << n;
++i;
}
}
std::cout << '\n';
}
int main() {
show_gapful_numbers(100, 30);
show_gapful_numbers(1000000, 15);
show_gapful_numbers(1000000000, 10);
return 0;
}

View file

@ -0,0 +1,64 @@
using System;
namespace GapfulNumbers
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("The first 30 gapful numbers are: ");
/* Starting at 100, find 30 gapful numbers */
FindGap(100, 30);
Console.WriteLine("The first 15 gapful numbers > 1,000,000 are: ");
FindGap(1000000, 15);
Console.WriteLine("The first 10 gapful numbers > 1,000,000,000 are: ");
FindGap(1000000000, 10);
Console.Read();
}
public static int firstNum(int n)
{
/*Divide by ten until the leading digit remains.*/
while (n >= 10)
{
n /= 10;
}
return (n);
}
public static int lastNum(int n)
{
/*Modulo gives you the last digit. */
return (n % 10);
}
static void FindGap(int n, int gaps)
{
int count = 0;
while (count < gaps)
{
/* We have to convert our first and last digits to strings to concatenate.*/
string concat = firstNum(n).ToString() + lastNum(n).ToString();
/* And then convert our concatenated string back to an integer. */
int i = Convert.ToInt32(concat);
/* Modulo with our new integer and output the result. */
if (n % i == 0)
{
Console.Write(n + " ");
count++;
n++;
}
else
{
n++;
continue;
}
}
}
}
}

View file

@ -0,0 +1,35 @@
#include<stdio.h>
void generateGaps(unsigned long long int start,int count){
int counter = 0;
unsigned long long int i = start;
char str[100];
printf("\nFirst %d Gapful numbers >= %llu :\n",count,start);
while(counter<count){
sprintf(str,"%llu",i);
if((i%(10*(str[0]-'0') + i%10))==0L){
printf("\n%3d : %llu",counter+1,i);
counter++;
}
i++;
}
}
int main()
{
unsigned long long int i = 100;
int count = 0;
char str[21];
generateGaps(100,30);
printf("\n");
generateGaps(1000000,15);
printf("\n");
generateGaps(1000000000,15);
printf("\n");
return 0;
}

View file

@ -0,0 +1,48 @@
IDENTIFICATION DIVISION.
PROGRAM-ID. GAPFUL.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 COMPUTATION.
02 N PIC 9(10).
02 N-DIGITS REDEFINES N.
03 ND PIC 9 OCCURS 10 TIMES.
02 DIV-CHECK PIC 9(10)V9(2).
02 DIV-PARTS REDEFINES DIV-CHECK.
03 DIV-INT PIC 9(10).
03 DIV-FRAC PIC 9(2).
02 GAP-AMOUNT PIC 99.
02 GAP-DSOR PIC 99.
02 FIRST-DIGIT PIC 99.
01 OUTPUT-FORMAT.
02 N-OUT PIC Z(10).
PROCEDURE DIVISION.
BEGIN.
DISPLAY "First 30 gapful numbers >= 100:".
MOVE 100 TO N. MOVE 30 TO GAP-AMOUNT.
PERFORM CHECK-GAPFUL-NUMBER.
DISPLAY " ".
DISPLAY "First 15 gapful numbers >= 1000000:".
MOVE 1000000 TO N. MOVE 15 TO GAP-AMOUNT.
PERFORM CHECK-GAPFUL-NUMBER.
DISPLAY " ".
DISPLAY "First 10 gapful numbers >= 1000000000:".
MOVE 1000000000 TO N. MOVE 10 TO GAP-AMOUNT.
PERFORM CHECK-GAPFUL-NUMBER.
STOP RUN.
CHECK-GAPFUL-NUMBER.
SET FIRST-DIGIT TO 1.
INSPECT N TALLYING FIRST-DIGIT FOR LEADING '0'.
COMPUTE GAP-DSOR = ND(FIRST-DIGIT) * 10 + ND(10).
DIVIDE N BY GAP-DSOR GIVING DIV-CHECK.
IF DIV-FRAC IS EQUAL TO 0
MOVE N TO N-OUT
DISPLAY N-OUT
SUBTRACT 1 FROM GAP-AMOUNT.
ADD 1 TO N.
IF GAP-AMOUNT IS GREATER THAN 0
GO TO CHECK-GAPFUL-NUMBER.

View file

@ -0,0 +1,21 @@
(defn first-digit [n] (Integer/parseInt (subs (str n) 0 1)))
(defn last-digit [n] (mod n 10))
(defn bookend-number [n] (+ (* 10 (first-digit n)) (last-digit n)))
(defn is-gapful? [n] (and (>= n 100) (zero? (mod n (bookend-number n)))))
(defn gapful-from [n] (filter is-gapful? (iterate inc n)))
(defn gapful [] (gapful-from 1))
(defn gapfuls-in-range [start size] (take size (gapful-from start)))
(defn report-range [[start size]]
(doall (map println
[(format "First %d gapful numbers >= %d:" size start)
(gapfuls-in-range start size)
""])))
(doall (map report-range [ [1 30] [1000000 15] [1000000000 10] ]))

View file

@ -0,0 +1,19 @@
100 DEF FNFD(N) = VAL(MID$(STR$(N),2,1))
110 DEF FNLD(N) = N - 10 * INT(N/10)
120 DEF FNBE(N) = 10 * FNFD(N) + FNLD(N)
130 DEF FNGF(N) = (N >= 100) AND (N - FNBE(N)*INT(N/FNBE(N)) = 0)
140 READ S:IF S<0 THEN 260
150 READ C
160 PRINT"THE FIRST"C"GAPFUL NUMBERS >="S":"
170 I=S:F=0
180 IF NOT FNGF(I) THEN 220
190 PRINT I,
200 F=F+1
210 IF F>=C THEN 240
220 I=I+1
230 GOTO 180
240 PRINT:PRINT
250 GOTO 140
260 END
270 DATA 1,30, 1000000,15, 100000000,10
280 DATA -1

View file

@ -0,0 +1,21 @@
(defun first-digit (n) (parse-integer (string (char (write-to-string n) 0))))
(defun last-digit (n) (mod n 10))
(defun bookend-number (n) (+ (* 10 (first-digit n)) (last-digit n)))
(defun gapfulp (n) (and (>= n 100) (zerop (mod n (bookend-number n)))))
(defun gapfuls-in-range (start size)
(loop for n from start
with include = (gapfulp n)
counting include into found
if include collecting n
until (= found size)))
(defun report-range (range)
(destructuring-bind (start size) range
(format t "The first ~a gapful numbers >= ~a:~% ~a~%~%" size start
(gapfuls-in-range start size))))
(mapcar #'report-range '((1 30) (1000000 15) (1000000000 10)))

View file

@ -0,0 +1,13 @@
struct Int
def gapful?
a = self.to_s.chars.map(&.to_i)
self % (a.first*10 + a.last) == 0
end
end
specs = {100 => 30, 1_000_000 => 15, 1_000_000_000 => 10, 7123 => 25}
specs.each do |start, count|
puts "first #{count} gapful numbers >= #{start}:"
puts (start..).each.select(&.gapful?).first(count).to_a, "\n"
end

View file

@ -0,0 +1,15 @@
struct Int
def gapful?
a = self.to_s.chars.map(&.to_i)
self % (a.first*10 + a.last) == 0
end
end
specs = {100 => 30, 1_000_000 => 15, 1_000_000_000 => 10, 7123 => 25}
specs.each do |start, count|
puts "first #{count} gapful numbers >= #{start}:"
i, gapful = 0, [] of Int32
(start..).each { |n| n.gapful? && (gapful << n; i += 1); break if i == count }
puts gapful, "\n"
end

View file

@ -0,0 +1,42 @@
import std.conv;
import std.stdio;
string commatize(ulong n) {
auto s = n.to!string;
auto le = s.length;
for (int i = le - 3; i >= 1; i -= 3) {
s = s[0..i]
~ ","
~ s[i..$];
}
return s;
}
void main() {
ulong[] starts = [cast(ulong)1e2, cast(ulong)1e6, cast(ulong)1e7, cast(ulong)1e9, 7123];
int[] counts = [30, 15, 15, 10, 25];
for (int i = 0; i < starts.length; i++) {
int count = 0;
auto j = starts[i];
ulong pow = 100;
while (true) {
if (j < pow * 10) {
break;
}
pow *= 10;
}
writefln("First %d gapful numbers starting at %s:", counts[i], commatize(starts[i]));
while (count < counts[i]) {
auto fl = (j / pow) * 10 + (j % 10);
if (j % fl == 0) {
write(j, ' ');
count++;
}
j++;
if (j >= 10 * pow) {
pow *= 10;
}
}
writeln("\n");
}
}

View file

@ -0,0 +1,11 @@
-module(gapful).
-export([first_digit/1, last_digit/1, bookend_number/1, is_gapful/1]).
first_digit(N) ->
list_to_integer(string:slice(integer_to_list(N),0,1)).
last_digit(N) -> N rem 10.
bookend_number(N) -> 10 * first_digit(N) + last_digit(N).
is_gapful(N) -> (N >= 100) and (0 == N rem bookend_number(N)).

View file

@ -0,0 +1,39 @@
-module(stream).
-export([yield/1, naturals/0, naturals/1, filter/2, take/2, to_list/1]).
yield(F) when is_function(F) -> F().
naturals() -> naturals(1).
naturals(N) -> fun() -> {N, naturals(N+1)} end.
filter(Pred, Stream) ->
fun() -> do_filter(Pred, Stream) end.
do_filter(Pred, Stream) ->
case yield(Stream) of
{X, Xs} ->
case Pred(X) of
true -> {X, filter(Pred, Xs)};
false -> do_filter(Pred, Xs)
end;
halt -> halt
end.
take(N, Stream) when N >= 0 ->
fun() ->
case yield(Stream) of
{X, Xs} ->
case N of
0 -> halt;
_ -> {X, take(N - 1, Xs)}
end;
halt -> halt
end
end.
to_list(Stream) -> to_list(Stream, []).
to_list(Stream, Acc) ->
case yield(Stream) of
{X, Xs} -> to_list(Xs, [X|Acc]);
halt -> lists:reverse(Acc)
end.

View file

@ -0,0 +1,9 @@
-module(gapful_demo).
-mode(compile).
report_range([Start, Size]) ->
io:fwrite("The first ~w gapful numbers >= ~w:~n~w~n~n", [Size, Start,
stream:to_list(stream:take(Size, stream:filter(fun gapful:is_gapful/1,
stream:naturals(Start))))]).
main(_) -> lists:map(fun report_range/1, [[1,30],[1000000,15],[1000000000,10]]).

View file

@ -0,0 +1,10 @@
USING: formatting kernel lists lists.lazy math math.functions
math.text.utils sequences ;
: gapful? ( n -- ? )
dup 1 digit-groups [ first ] [ last 10 * + ] bi divisor? ;
30 100 15 1,000,000 10 1,000,000,000 [
2dup lfrom [ gapful? ] lfilter ltake list>array
"%d gapful numbers starting at %d:\n%[%d, %]\n\n" printf
] 2tri@

View file

@ -0,0 +1,20 @@
variable cnt
: Int>Str s>d <# #s #> ;
: firstDigit C@ [char] 0 - ;
: lastDigit + 1- c@ [char] 0 - ;
: cnt++ cnt dup @ 1+ dup rot ! ;
: GapfulNumber? dup dup Int>Str
2dup drop firstDigit 10 *
-rot lastDigit +
/mod drop 0= ;
: main 0 cnt ! 2dup
cr ." First " . ." gapful numbers >= " .
begin dup cnt @ -
while swap GapfulNumber?
if dup cr cnt++ . ." : " . then
1+ swap
repeat 2drop ;
100 30 main cr
1000000 15 main cr
1000000000 10 main cr

View file

@ -0,0 +1,38 @@
function is_gapful( n as uinteger ) as boolean
if n<100 then return false
dim as string ns = str(n)
dim as uinteger gap = 10*val(mid(ns,1,1)) + val(mid(ns,len(ns),1))
if n mod gap = 0 then return true else return false
end function
dim as ulongint i = 100
dim as ushort c
print "The first thirty gapful numbers:"
while c<30
if is_gapful(i) then
c += 1
print i;" ";
end if
i += 1
wend
print : print
i = 1000000 : c = 0
print "The first fifteen gapful numbers above 999,999:"
while c<15
if is_gapful(i) then
c += 1
print i;" ";
end if
i += 1
wend
print : print
i = 1000000000 : c = 0
print "The first ten gapful numbers above 999,999,999:"
while c<10
if is_gapful(i) then
c += 1
print i;" ";
end if
i += 1
wend
print

View file

@ -0,0 +1,32 @@
// Create function to calculate gapful number
gapful[num,totalCounter] :=
{
// Display a line explaining the current calculation.
println["First $totalCounter gapful numbers over $num:"]
// Start a counter to compare with the total count.
counter = 0
while counter < totalCounter
{
numStr = toString[num] // Convert the integer to a string
gapfulNumStr = left[numStr,1] + right[numStr,1] // Concatenate the first and last character of the number to form a two digit number
gapfulNumInt = parseInt[gapfulNumStr] // Turn the concatenated string back into an integer.
// If the concatenated two digit integer divides into the current num variable with no remainder, print it to the list and increase our counter
if num mod gapfulNumInt == 0
{
print[numStr + " "]
counter = counter + 1
}
// Increase the current number for the next cycle.
num = num + 1
}
p
rintln[] // Linkbreak
}
// Print the first 30 gapful numbers over 100, the top 15 over 1,000,000 and the first 10 over 1,000,000,000.
gapful[100,30]
gapful[1000000,15]
gapful[1000000000,10]

View file

@ -0,0 +1,30 @@
include "NSLog.incl"
_0 = 48 // ASCII code for 0 = 48
void local fn GenerateGaps( start as UInt64, count as NSInteger )
NSInteger counter = 0
UInt64 i = start
NSLog( @"First %d Gapful numbers >= %llu:", count, start )
while ( counter < count )
CFStringRef string = fn StringWithFormat( @"%llu", i )
UniChar character = fn StringCharacterAtIndex( string, 0 )
if( ( i mod ( 10 * ( character - _0 ) + i mod 10 ) ) == 0 )
NSLog( @"%3d : %llu", counter + 1, i )
counter++
end if
i++
wend
end fn
local fn DoIt
fn generateGaps( 100, 30 ) : NSLog( @"\n" )
fn generateGaps( 1000000, 15 ) : NSLog( @"\n" )
fn generateGaps( 1000000000, 15 ) : NSLog( @"\n" )
end fn
fn DoIt
HandleEvents

View file

@ -0,0 +1,41 @@
package main
import "fmt"
func commatize(n uint64) string {
s := fmt.Sprintf("%d", n)
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
return s
}
func main() {
starts := []uint64{1e2, 1e6, 1e7, 1e9, 7123}
counts := []int{30, 15, 15, 10, 25}
for i := 0; i < len(starts); i++ {
count := 0
j := starts[i]
pow := uint64(100)
for {
if j < pow*10 {
break
}
pow *= 10
}
fmt.Printf("First %d gapful numbers starting at %s:\n", counts[i], commatize(starts[i]))
for count < counts[i] {
fl := (j/pow)*10 + (j % 10)
if j%fl == 0 {
fmt.Printf("%d ", j)
count++
}
j++
if j >= 10*pow {
pow *= 10
}
}
fmt.Println("\n")
}
}

View file

@ -0,0 +1,39 @@
class GapfulNumbers {
private static String commatize(long n) {
StringBuilder sb = new StringBuilder(Long.toString(n))
int le = sb.length()
for (int i = le - 3; i >= 1; i -= 3) {
sb.insert(i, ',')
}
return sb.toString()
}
static void main(String[] args) {
List<Long> starts = [(long) 1e2, (long) 1e6, (long) 1e7, (long) 1e9, (long) 7123]
List<Integer> counts = [30, 15, 15, 10, 25]
for (int i = 0; i < starts.size(); ++i) {
println("First ${counts.get(i)} gapful numbers starting at ${commatize(starts.get(i))}")
long j = starts.get(i)
long pow = 100
while (j >= pow * 10) {
pow *= 10
}
int count = 0
while (count < counts.get(i)) {
long fl = ((long) (j / pow)) * 10 + (j % 10)
if (j % fl == 0) {
print("$j ")
count++
}
if (++j >= 10 * pow) {
pow *= 10
}
}
println()
println()
}
}
}

View file

@ -0,0 +1,14 @@
{-# LANGUAGE NumericUnderscores #-}
gapful :: Int -> Bool
gapful n = n `rem` firstLastDigit == 0
where
firstLastDigit = read [head asDigits, last asDigits]
asDigits = show n
main :: IO ()
main = do
putStrLn $ "\nFirst 30 Gapful numbers >= 100 :\n" ++ r 30 [100,101..]
putStrLn $ "\nFirst 15 Gapful numbers >= 1,000,000 :\n" ++ r 15 [1_000_000,1_000_001..]
putStrLn $ "\nFirst 10 Gapful numbers >= 1,000,000,000 :\n" ++ r 10 [1_000_000_000,1_000_000_001..]
where r n = show . take n . filter gapful

View file

@ -0,0 +1,33 @@
import Data.List (intercalate)
import Data.List.Split (chunksOf)
---------------------- GAPFUL NUMBERS --------------------
isGapful :: Int -> Bool
isGapful =
(0 ==)
. (<*>)
rem
(read . (<*>) [head, last] . pure . show)
--------------------------- TEST -------------------------
main :: IO ()
main =
mapM_
(putStrLn . showSample)
[ "First 30 gapful numbers >= 100",
"First 15 Gapful numbers >= 1000000",
"First 10 Gapful numbers >= 1000000000"
]
showSample :: String -> String
showSample k =
let ws = words k
in k <> ":\n\n"
<> unlines
( fmap (intercalate ", " . fmap show) $
chunksOf 5 $
take
(read (ws !! 1))
[read (ws !! 5) :: Int ..]
)

View file

@ -0,0 +1,7 @@
gapful =: 0 = (|~ ({.,{:)&.(10&#.inv))
task =: 100&$: :(dyad define) NB. MINIMUM task TALLY
gn =. y {. (#~ gapful&>) x + i. y * 25
assert 0 ~: {: gn
'The first ' , (": y) , ' gapful numbers exceeding ' , (":<:x) , ' are ' , (":gn)
)

View file

@ -0,0 +1,38 @@
import java.util.List;
public class GapfulNumbers {
private static String commatize(long n) {
StringBuilder sb = new StringBuilder(Long.toString(n));
int le = sb.length();
for (int i = le - 3; i >= 1; i -= 3) {
sb.insert(i, ',');
}
return sb.toString();
}
public static void main(String[] args) {
List<Long> starts = List.of((long) 1e2, (long) 1e6, (long) 1e7, (long) 1e9, (long) 7123);
List<Integer> counts = List.of(30, 15, 15, 10, 25);
for (int i = 0; i < starts.size(); ++i) {
int count = 0;
Long j = starts.get(i);
long pow = 100;
while (j >= pow * 10) {
pow *= 10;
}
System.out.printf("First %d gapful numbers starting at %s:\n", counts.get(i), commatize(starts.get(i)));
while (count < counts.get(i)) {
long fl = (j / pow) * 10 + (j % 10);
if (j % fl == 0) {
System.out.printf("%d ", j);
count++;
}
j++;
if (j >= 10 * pow) {
pow *= 10;
}
}
System.out.println('\n');
}
}
}

View file

@ -0,0 +1,56 @@
// Function to construct a new integer from the first and last digits of another
function gapfulness_divisor (number) {
var digit_string = number.toString(10)
var digit_count = digit_string.length
var first_digit = digit_string.substring(0, 1)
var last_digit = digit_string.substring(digit_count - 1)
return parseInt(first_digit.concat(last_digit), 10)
}
// Divisibility test to determine gapfulness
function is_gapful (number) {
return number % gapfulness_divisor(number) == 0
}
// Function to search for the least gapful number greater than a given integer
function next_gapful (number) {
do {
++number
} while (!is_gapful(number))
return number
}
// Constructor for a list of gapful numbers starting from given lower bound
function gapful_numbers (start, amount) {
var list = [], count = 0, number = start
if (amount > 0 && is_gapful(start)) {
list.push(start)
}
while (list.length < amount) {
number = next_gapful(number)
list.push(number)
}
return list
}
// Formatter for a comma-separated list of gapful numbers
function single_line_gapfuls (start, amount) {
var list = gapful_numbers(start, amount)
return list.join(", ")
}
// Windows console output wrapper
function print(message) {
WScript.StdOut.WriteLine(message)
}
// Main algorithm
function print_gapfuls_with_header(start, amount) {
print("First " + start + " gapful numbers starting at " + amount)
print(single_line_gapfuls(start, amount))
}
print_gapfuls_with_header(100, 30)
print_gapfuls_with_header(1000000, 15)
print_gapfuls_with_header(1000000000, 10)

View file

@ -0,0 +1,208 @@
(() => {
'use strict';
// ------------------ GAPFUL NUMBERS -------------------
// isGapful :: Int -> Bool
const isGapful = n =>
compose(
x => 0 === n % x,
JSON.parse,
concat,
ap([head, last]),
x => [x],
JSON.stringify
)(n);
// ----------------------- TEST ------------------------
const main = () =>
unlines([
'First 30 gapful numbers >= 100',
'First 15 Gapful numbers >= 1E6',
'First 10 Gapful numbers >= 1E9'
].map(k => {
const
ws = words(k),
mn = [1, 5].map(
i => JSON.parse(ws[i])
);
return k + ':\n\n' + showList(
take(mn[0])(
filterGen(isGapful)(
enumFrom(mn[1])
)
)
);
}));
// ----------------- GENERIC FUNCTIONS -----------------
// ap (<*>) :: [(a -> b)] -> [a] -> [b]
const ap = fs =>
// The sequential application of each of a list
// of functions to each of a list of values.
xs => fs.flatMap(f => xs.map(x => f(x)));
// chunksOf :: Int -> [a] -> [[a]]
const chunksOf = n =>
xs => enumFromThenTo(0)(n)(
xs.length - 1
).reduce(
(a, i) => a.concat([xs.slice(i, (n + i))]),
[]
);
// compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
const compose = (...fs) =>
// A function defined by the right-to-left
// composition of all the functions in fs.
fs.reduce(
(f, g) => x => f(g(x)),
x => x
);
// concat :: [[a]] -> [a]
// concat :: [String] -> String
const concat = xs => (
ys => 0 < ys.length ? (
ys.every(Array.isArray) ? (
[]
) : ''
).concat(...ys) : ys
)(list(xs));
// enumFrom :: Enum a => a -> [a]
function* enumFrom(x) {
// A non-finite succession of enumerable
// values, starting with the value x.
let v = x;
while (true) {
yield v;
v = succ(v);
}
}
// enumFromThenTo :: Int -> Int -> Int -> [Int]
const enumFromThenTo = x1 =>
x2 => y => {
const d = x2 - x1;
return Array.from({
length: Math.floor(y - x2) / d + 2
}, (_, i) => x1 + (d * i));
};
// filterGen :: (a -> Bool) -> Gen [a] -> [a]
const filterGen = p => xs => {
function* go() {
let x = xs.next();
while (!x.done) {
let v = x.value;
if (p(v)) {
yield v;
}
x = xs.next();
}
}
return go(xs);
};
// head :: [a] -> a
const head = xs => (
ys => ys.length ? (
ys[0]
) : undefined
)(list(xs));
// last :: [a] -> a
const last = xs => (
// The last item of a list.
ys => 0 < ys.length ? (
ys.slice(-1)[0]
) : undefined
)(list(xs));
// list :: StringOrArrayLike b => b -> [a]
const list = xs =>
// xs itself, if it is an Array,
// or an Array derived from xs.
Array.isArray(xs) ? (
xs
) : Array.from(xs || []);
// showList :: [a] -> String
const showList = xs =>
unlines(
chunksOf(5)(xs).map(
ys => '\t' + ys.join(',')
)
) + '\n';
// succ :: Enum a => a -> a
const succ = x => {
const t = typeof x;
return 'number' !== t ? (() => {
const [i, mx] = [x, maxBound(x)].map(fromEnum);
return i < mx ? (
toEnum(x)(1 + i)
) : Error('succ :: enum out of range.')
})() : x < Number.MAX_SAFE_INTEGER ? (
1 + x
) : Error('succ :: Num out of range.')
};
// take :: Int -> [a] -> [a]
// take :: Int -> String -> String
const take = n =>
// The first n elements of a list,
// string of characters, or stream.
xs => 'GeneratorFunction' !== xs
.constructor.constructor.name ? (
xs.slice(0, n)
) : [].concat.apply([], Array.from({
length: n
}, () => {
const x = xs.next();
return x.done ? [] : [x.value];
}));
// toEnum :: a -> Int -> a
const toEnum = e =>
// The first argument is a sample of the type
// allowing the function to make the right mapping
x => ({
'number': Number,
'string': String.fromCodePoint,
'boolean': Boolean,
'object': v => e.min + v
} [typeof e])(x);
// unlines :: [String] -> String
const unlines = xs =>
// A single string formed by the intercalation
// of a list of strings with the newline character.
xs.join('\n');
// words :: String -> [String]
const words = s =>
// List of space-delimited sub-strings.
s.split(/\s+/);
// MAIN ---
return main();
})();

View file

@ -0,0 +1,15 @@
# emit a stream of gapful numbers greater than or equal to $start,
# which is assumed to be an integer
def gapful($start):
range($start; infinite)
| . as $i
| tostring as $s
| (($s[:1] + $s[-1:]) | tonumber) as $x
| select($i % $x == 0);
"First 30 gapful numbersstarting from 100:",
([limit(30;gapful(100))] | join(" ")),
"First 15 gapful numbers starting from 1,000,000:",
([limit(15;gapful(1000000))] | join(" ")),
"First 10 gapful numbers starting from 10^9:",
([limit(10;gapful(pow(10;9)))] | join(" "))

View file

@ -0,0 +1,10 @@
using Lazy, Formatting
firstlast(a) = 10 * a[end] + a[1]
isgapful(n) = (d = digits(n); length(d) < 3 || (m = firstlast(d)) != 0 && mod(n, m) == 0)
gapfuls(start) = filter(isgapful, Lazy.range(start))
for (x, n) in [(100, 30), (1_000_000, 15), (1_000_000_000, 10)]
println("First $n gapful numbers starting at ", format(x, commas=true), ":\n",
take(n, gapfuls(x)))
end

View file

@ -0,0 +1,40 @@
private fun commatize(n: Long): String {
val sb = StringBuilder(n.toString())
val le = sb.length
var i = le - 3
while (i >= 1) {
sb.insert(i, ',')
i -= 3
}
return sb.toString()
}
fun main() {
val starts = listOf(1e2.toLong(), 1e6.toLong(), 1e7.toLong(), 1e9.toLong(), 7123.toLong())
val counts = listOf(30, 15, 15, 10, 25)
for (i in starts.indices) {
var count = 0
var j = starts[i]
var pow: Long = 100
while (j >= pow * 10) {
pow *= 10
}
System.out.printf(
"First %d gapful numbers starting at %s:\n",
counts[i],
commatize(starts[i])
)
while (count < counts[i]) {
val fl = j / pow * 10 + j % 10
if (j % fl == 0L) {
System.out.printf("%d ", j)
count++
}
j++
if (j >= 10 * pow) {
pow *= 10
}
}
println('\n')
}
}

View file

@ -0,0 +1,64 @@
HAI 1.2
HOW IZ I FurstDigit YR Numbr
I HAS A Digit
IM IN YR Loop NERFIN YR Dummy WILE DIFFRINT Numbr AN 0
Digit R MOD OF Numbr AN 10
Numbr R QUOSHUNT OF Numbr AN 10
IM OUTTA YR Loop
FOUND YR Digit
IF U SAY SO
HOW IZ I LastDigit YR Numbr
FOUND YR MOD OF Numbr AN 10
IF U SAY SO
HOW IZ I Bookend YR Numbr
FOUND YR SUM OF PRODUKT OF I IZ FurstDigit YR Numbr MKAY AN 10 AN I IZ LastDigit YR Numbr MKAY
IF U SAY SO
HOW IZ I CheckGapful YR Numbr
I HAS A Bookend ITZ I IZ Bookend YR Numbr MKAY
I HAS A BigEnuff ITZ BOTH SAEM Numbr AN BIGGR OF Numbr AN 100
FOUND YR BOTH OF BigEnuff AN BOTH SAEM 0 AN MOD OF Numbr AN Bookend
IF U SAY SO
HOW IZ I FindGapfuls YR Start AN YR HowMany
I HAS A Numbr ITZ Start
I HAS A Anser ITZ A BUKKIT
I HAS A Found ITZ 0
IM IN YR Loop UPPIN YR Dummy WILE DIFFRINT Found AN HowMany
I IZ CheckGapful YR Numbr MKAY
O RLY?
YA RLY
Anser HAS A SRS Found ITZ Numbr
Found R SUM OF Found AN 1
OIC
Numbr R SUM OF Numbr AN 1
IM OUTTA YR Loop
FOUND YR Anser
IF U SAY SO
HOW IZ I Report YR Start AN YR HowMany
VISIBLE "The furst " !
VISIBLE HowMany !
VISIBLE " Gapful numbrs starting with " !
VISIBLE Start !
VISIBLE "::"
I HAS A Anser ITZ I IZ FindGapfuls YR Start AN YR HowMany MKAY
IM IN YR Loop UPPIN YR Index TIL BOTH SAEM Index AN HowMany
DIFFRINT Index AN 0
O RLY?
YA RLY
VISIBLE ", " !
OIC
VISIBLE Anser'Z SRS Index !
IM OUTTA YR Loop
VISIBLE ""
VISIBLE ""
IF U SAY SO
I IZ Report YR 1 AN YR 30 MKAY
I IZ Report YR 1000000 AN YR 15 MKAY
I IZ Report YR 1000000000 AN YR 10 MKAY
KTHXBYE

View file

@ -0,0 +1,20 @@
{def gapfuls
{lambda {:n :i :N}
{if {>= :i :N}
then
else {if {= {% :n {W.first :n}{W.last :n}} 0}
then :n {gapfuls {+ :n 1} {+ :i 1} :N}
else {gapfuls {+ :n 1} :i :N}}}}}
-> gapfuls
{gapfuls 100 0 30}
-> 100 105 108 110 120 121 130 132 135 140 143 150 154 160 165 170 176 180
187 190 192 195 198 200 220 225 231 240 242 253
{gapfuls 1000000 0 15}
-> 1000000 1000005 1000008 1000010 1000016 1000020 1000021
1000030 1000032 1000034 1000035 1000040 1000050 1000060 1000065
{gapfuls 1000000000 0 10}
-> 1000000000 1000000001 1000000005 1000000008 1000000010
1000000016 1000000020 1000000027 1000000030 1000000032

View file

@ -0,0 +1,28 @@
to bookend_number :n
output sum product 10 first :n last :n
end
to gapful? :n
output and greaterequal? :n 100 equal? 0 modulo :n bookend_number :n
end
to gapfuls_in_range :start :size
localmake "gapfuls []
do.while [
if (gapful? :start) [
make "gapfuls (lput :start gapfuls)
]
make "start sum :start 1
] [less? (count :gapfuls) :size]
output :gapfuls
end
to report_range :start :size
print (word "|The first | :size "| gapful numbers >= | :start "|:|)
print gapfuls_in_range :start :size
(print)
end
foreach [ [1 30] [1000000 15] [1000000000 10] ] [
apply "report_range ?
]

View file

@ -0,0 +1,25 @@
function generateGaps(start, count)
local counter = 0
local i = start
print(string.format("First %d Gapful numbers >= %d :", count, start))
while counter < count do
local str = tostring(i)
local denom = 10 * tonumber(str:sub(1, 1)) + (i % 10)
if i % denom == 0 then
print(string.format("%3d : %d", counter + 1, i))
counter = counter + 1
end
i = i + 1
end
end
generateGaps(100, 30)
print()
generateGaps(1000000, 15)
print()
generateGaps(1000000000, 15)
print()

View file

@ -0,0 +1,23 @@
ClearAll[GapFulQ]
GapFulQ[n_Integer] := Divisible[n, FromDigits[IntegerDigits[n][[{1, -1}]]]]
i = 100;
res = {};
While[Length[res] < 30,
If[GapFulQ[i], AppendTo[res, i]];
i++
]
res
i = 10^6;
res = {};
While[Length[res] < 15,
If[GapFulQ[i], AppendTo[res, i]];
i++
]
res
i = 10^9;
res = {};
While[Length[res] < 10,
If[GapFulQ[i], AppendTo[res, i]];
i++
]
res

View file

@ -0,0 +1,23 @@
(() 0 shorten) :new
(((10 mod) (10 div)) cleave) :moddiv
((dup 0 ==) (pop new) 'moddiv 'cons linrec) :digits
(digits ((last 10 *) (first +)) cleave) :flnum
(mod 0 ==) :divisor?
(dup flnum divisor?) :gapful?
(
:target :n 0 :count
"$1 gapful numbers starting at $2:" (target n) => % puts!
(count target <) (
(n gapful?) (
count succ @count
n print! " " print!
) when
n succ @n
) while
newline
) :show-gapfuls
100 30 show-gapfuls newline
1000000 15 show-gapfuls newline
1000000000 10 show-gapfuls

View file

@ -0,0 +1,49 @@
; Part 1: Useful functions
;; Create an integer out of the first and last digits of a given integer
(define (first-and-last-digits number)
(local (digits first-digit last-digit)
(set 'digits (format "%d" number))
(set 'first-digit (first digits))
(set 'last-digit (last digits))
(int (append first-digit last-digit))))
;; Divisbility test
(define (divisible-by? num1 num2)
(zero? (% num1 num2)))
;; Gapfulness test
(define (gapful? number)
(divisible-by? number (first-and-last-digits number)))
;; Increment until a gapful number is found
(define (next-gapful-after number)
(do-until (gapful? number)
(++ number)))
;; Return a list of gapful numbers beyond some (excluded) lower limit.
(define (gapful-numbers quantity lower-limit)
(let ((gapfuls '()) (number lower-limit))
(dotimes (counter quantity)
(set 'number (next-gapful-after number))
(push number gapfuls))
(reverse gapfuls)))
;; Format a list of numbers together into decimal notation.
(define (format-many numbers)
(map (curry format "%d") numbers))
;; Format a list of integers on one line with commas
(define (format-one-line numbers)
(join (format-many numbers) ", "))
;; Display a quantity of gapful numbers beyond some (excluded) lower limit.
(define (show-gapfuls quantity lower-limit)
(println "The first " quantity " gapful numbers beyond " lower-limit " are:")
(println (format-one-line (gapful-numbers quantity lower-limit))))
; Part 2: Complete the task
(show-gapfuls 30 99)
(show-gapfuls 15 999999)
(show-gapfuls 10 999999999)
(exit)

View file

@ -0,0 +1,41 @@
import strutils
func gapfulDivisor(n: Positive): Positive =
## Return the gapful divisor of "n".
let last = n mod 10
var first = n div 10
while first > 9:
first = first div 10
result = 10 * first + last
iterator gapful(start: Positive): Positive =
## Yield the gapful numbers starting from "start".
var n = start
while true:
let d = n.gapfulDivisor()
if n mod d == 0: yield n
inc n
proc displayGapfulNumbers(start, num: Positive) =
## Display the first "num" gapful numbers greater or equal to "start".
echo "\nFirst $1 gapful numbers ⩾ $2:".format(num, start)
var count = 0
var line: string
for n in gapful(start):
line.addSep(" ")
line.add($n)
inc count
if count == num: break
echo line
when isMainModule:
displayGapfulNumbers(100, 30)
displayGapfulNumbers(1_000_000, 15)
displayGapfulNumbers(1_000_000_000, 10)

View file

@ -0,0 +1,15 @@
let rec first_digit x =
if x < 10 then x else first_digit (x / 10)
let is_gapful x =
x mod (10 * first_digit x + x mod 10) = 0
let fmt_seq x n =
Seq.(ints x |> filter is_gapful |> take n |> map string_of_int)
|> List.of_seq |> String.concat ", "
let () =
let fmt (x, n) =
Printf.printf "\nFirst %u gapful numbers from %u:\n%s\n" n x (fmt_seq x n)
in
List.iter fmt [100, 30; 1000000, 15; 1000000000, 10]

View file

@ -0,0 +1,49 @@
100H: /* FIND SOME GAPFUL NUMBERS: NUMBERS DIVISIBLE BY 10F + L WHERE F IS */
/* THE FIRST DIGIT AND L IS THE LAST DIGIT */
BDOS: PROCEDURE( FN, ARG ); /* CP/M BDOS SYSTEM CALL */
DECLARE FN BYTE, ARG ADDRESS;
GOTO 5;
END BDOS;
PR$CHAR: PROCEDURE( C ); DECLARE C BYTE; CALL BDOS( 2, C ); END;
PR$STRING: PROCEDURE( S ); DECLARE S ADDRESS; CALL BDOS( 9, S ); END;
PR$NL: PROCEDURE; CALL PR$CHAR( 0DH ); CALL PR$CHAR( 0AH ); END;
PR$NUMBER: PROCEDURE( N );
DECLARE N ADDRESS;
DECLARE V ADDRESS, N$STR( 6 ) BYTE, W BYTE;
V = N;
W = LAST( N$STR );
N$STR( W ) = '$';
N$STR( W := W - 1 ) = '0' + ( V MOD 10 );
DO WHILE( ( V := V / 10 ) > 0 );
N$STR( W := W - 1 ) = '0' + ( V MOD 10 );
END;
CALL PR$STRING( .N$STR( W ) );
END PR$NUMBER;
/* RETURNS TRUE IF N IS GAPFUL, FALSE OTHERWISE */
IS$GAPFUL: PROCEDURE( N )BYTE;
DECLARE N ADDRESS;
DECLARE F ADDRESS;
F = N / 10;
DO WHILE ( F > 9 );
F = F / 10;
END;
RETURN N MOD ( ( F * 10 ) + ( N MOD 10 ) ) = 0;
END IS$GAPFUL;
/* FIND THE FIRST 30 GAPFUL NUMBERS >= 100 */
CALL PR$STRING( .'FIRST 30 GAPFUL NUMBERS STARTING FROM 100:$' );
CALL PR$NL;
DECLARE N ADDRESS, G$COUNT BYTE;
G$COUNT = 0;
N = 100;
DO WHILE ( G$COUNT < 30 );
IF IS$GAPFUL( N ) THEN DO;
/* HAVE A GAPFUL NUMBER */
G$COUNT = G$COUNT + 1;
CALL PR$CHAR( ' ' );
CALL PR$NUMBER( N );
END;
N = N + 1;
END;
CALL PR$NL;
EOF

View file

@ -0,0 +1,180 @@
program gapful;
{$IFDEF FPC}
{$MODE DELPHI}{$OPTIMIZATION ON,ALL}
{$ELSE}
{$APPTYPE CONSOLE}
{$ENDIF}
uses
sysutils // IntToStr
{$IFDEF FPC}
,strUtils // Numb2USA aka commatize
{$ENDIF};
const
cIdx = 5;
starts: array[0..cIdx - 1] of Uint64 = (100, 1000 * 1000, 10 * 1000 * 1000,
1000 * 1000 * 1000, 7123);
counts: array[0..cIdx - 1] of Uint64 = (30, 15, 15, 10, 25);
//100| 74623687 => 1000*1000*1000
//100| 746236131 => 10*1000*1000*1000
//100|7462360431 =>100*1000*1000*1000
Base = 10;
var
ModsHL: array[0..99] of NativeUint;
Pow10: Uint64; //global, seldom used
countLmt: NativeUint; //Uint64; only for extreme counting
{$IFNDEF FPC}
function Numb2USA(const S: string): string;
var
i, NA: Integer;
begin
i := Length(S);
Result := S;
NA := 0;
while (i > 0) do
begin
if ((Length(Result) - i + 1 - NA) mod 3 = 0) and (i <> 1) then
begin
insert(',', Result, i);
inc(NA);
end;
Dec(i);
end;
end;
{$ENDIF}
procedure OutHeader(i: NativeInt);
begin
writeln('First ', counts[i], ', gapful numbers starting at ', Numb2USA(IntToStr
(starts[i])));
end;
procedure OutNum(n: Uint64);
begin
write(' ', n);
end;
procedure InitMods(n: Uint64; H_dgt: NativeUint);
//calculate first mod of n, when it reaches n
var
i, j: NativeInt;
begin
j := H_dgt; //= H_dgt+i
for i := 0 to Base - 1 do
begin
ModsHL[j] := n mod j;
inc(n);
inc(j);
end;
end;
procedure InitMods2(n: Uint64; H_dgt, L_Dgt: NativeUint);
//calculate first mod of n, when it reaches n
//beware, that the lower n are reached in the next base round
var
i, j: NativeInt;
begin
j := H_dgt;
n := n - L_Dgt;
for i := 0 to L_Dgt - 1 do
begin
ModsHL[j] := (n + base) mod j;
inc(n);
inc(j);
end;
for i := L_Dgt to Base - 1 do
begin
ModsHL[j] := n mod j;
inc(n);
inc(j);
end;
end;
procedure Main(TestNum: Uint64; Cnt: NativeUint);
var
LmtNextNewHiDgt: Uint64;
tmp, LowDgt, GapNum: NativeUint;
begin
countLmt := Cnt;
Pow10 := Base * Base;
LmtNextNewHiDgt := Base * Pow10;
while LmtNextNewHiDgt <= TestNum do
begin
Pow10 := LmtNextNewHiDgt;
LmtNextNewHiDgt := LmtNextNewHiDgt * Base;
end;
LowDgt := TestNum mod Base;
GapNum := TestNum div Pow10;
LmtNextNewHiDgt := (GapNum + 1) * Pow10;
GapNum := Base * GapNum;
if LowDgt <> 0 then
InitMods2(TestNum, GapNum, LowDgt)
else
InitMODS(TestNum, GapNum);
GapNum := GapNum + LowDgt;
repeat
// if TestNum MOD (GapNum) = 0 then
if ModsHL[GapNum] = 0 then
begin
tmp := countLmt - 1;
if tmp < 32 then
OutNum(TestNum);
countLmt := tmp;
// Test and BREAK only if something has changed
if tmp = 0 then
BREAK;
end;
tmp := Base + ModsHL[GapNum];
//translate into "if-less" version 3.35s -> 1.85s
//bad branch prediction :-(
//if tmp >= GapNum then tmp -= GapNum;
tmp := tmp - (-ORD(tmp >= GapNum) and GapNum);
ModsHL[GapNum] := tmp;
TestNum := TestNum + 1;
tmp := LowDgt + 1;
inc(GapNum);
if tmp >= Base then
begin
tmp := 0;
GapNum := GapNum - Base;
end;
LowDgt := tmp;
//next Hi Digit
if TestNum >= LmtNextNewHiDgt then
begin
LowDgt := 0;
GapNum := GapNum + Base;
LmtNextNewHiDgt := LmtNextNewHiDgt + Pow10;
//next power of 10
if GapNum >= Base * Base then
begin
Pow10 := Pow10 * Base;
LmtNextNewHiDgt := 2 * Pow10;
GapNum := Base;
end;
initMods(TestNum, GapNum);
end;
until false;
end;
var
i: integer;
begin
for i := 0 to High(starts) do
begin
OutHeader(i);
Main(starts[i], counts[i]);
writeln(#13#10);
end;
{$IFNDEF LINUX} readln; {$ENDIF}
end.

View file

@ -0,0 +1,95 @@
program gapful;
{$IFDEF FPC}
{$MODE DELPHI}{$OPTIMIZATION ON,ALL}
{$ELSE}
{$APPTYPE CONSOLE}
{$ENDIF}
uses
sysutils,// IntToStr
strUtils;// Numb2USA aka commatize
var
LCMsHL : array of NativeInt;
function GCD(a, b: Int64): Int64;
var
temp: Int64;
begin
while b <> 0 do
begin
temp := b;
b := a mod b;
a := temp
end;
result := a
end;
function LCM(a, b: Int64): Int64;
begin
LCM := (a DIV GCD(a,b)) * b;
end;
procedure InitLCM(Base:NativeInt);
var
i : integer;
Begin
For i := Base to (Base*Base-1) do
LCMsHL[i] := LCM(i,Base);
end;
function CountGapFul(H_Digit,Base:NativeInt;PotBase:Uint64):Uint64;
//Counts gapfulnumbers [n*PotBase..(n+1)*PotBase -1] ala [100..199]
var
EndDgt,Dgt : NativeInt;
P,k,lmt,sum,dSum: UInt64;
begin
P := PotBase*H_Digit;
lmt := P+PotBase-1;
Dgt := H_Digit*Base;
sum := (PotBase-1) DIV dgt +1;
For EndDgt := 1 to Base-1 do
Begin
inc(Dgt);
//search start
//first value divisible by dgt
k := p-(p MOD dgt)+ dgt;
//value divisible by dgt ending in the right digit
while (k mod Base) <> EndDgt do
inc(k,dgt);
IF k> lmt then
continue;
//one found +1
//count the occurences in (lmt-k)
dSum := (lmt-k) DIV LCMsHL[dgt] +1;
inc(sum,dSum);
//writeln(dgt:5,k:21,dSum:21,Sum:21);
end;
//writeln(p:21,Sum:21);
CountGapFul := sum;
end;
procedure Main(Base:NativeUInt);
var
i : NativeUInt;
pot,total,lmt: Uint64;//High(Uint64) = 2^64-1
Begin
lmt := High(pot) DIV Base;
pot := sqr(Base);//"100" in Base
setlength(LCMsHL,pot);
InitLCM(Base);
total := 0;
repeat
IF pot > lmt then
break;
For i := 1 to Base-1 do //ala 100..199 ,200..299,300..399,..,900..999
inc(total,CountGapFul(i,base,pot));
pot *= Base;
writeln('Total [',sqr(Base),'..',Numb2USA(IntToStr(pot)),'] : ',Numb2USA(IntToStr(total+1)));
until false;
setlength(LCMsHL,0);
end;
BEGIN
Main(10);
Main(100);
END.

View file

@ -0,0 +1,16 @@
use strict;
use warnings;
use feature 'say';
sub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ s/^,//r }
sub is_gapful { my $n = shift; 0 == $n % join('', (split //, $n)[0,-1]) }
use constant Inf => 1e10;
for ([1e2, 30], [1e6, 15], [1e9, 10], [7123, 25]) {
my($start, $count) = @$_;
printf "\nFirst $count gapful numbers starting at %s:\n", comma $start;
my $n = 0; my $g = '';
$g .= do { $n < $count ? (is_gapful($_) and ++$n and "$_ ") : last } for $start .. Inf;
say $g;
}

View file

@ -0,0 +1,23 @@
(phixonline)-->
<span style="color: #008080;">constant</span> <span style="color: #000000;">starts</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">1e2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">1e6</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">1e7</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">1e9</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">7123</span><span style="color: #0000FF;">},</span>
<span style="color: #000000;">counts</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">30</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">15</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">15</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">10</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">25</span><span style="color: #0000FF;">}</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">starts</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">count</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">counts</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span>
<span style="color: #000000;">j</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">starts</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span>
<span style="color: #000000;">pow</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">100</span>
<span style="color: #008080;">while</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">>=</span><span style="color: #000000;">pow</span><span style="color: #0000FF;">*</span><span style="color: #000000;">10</span> <span style="color: #008080;">do</span> <span style="color: #000000;">pow</span> <span style="color: #0000FF;">*=</span> <span style="color: #000000;">10</span> <span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"First %d gapful numbers starting at %,d: "</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">count</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">while</span> <span style="color: #000000;">count</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">fl</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">j</span><span style="color: #0000FF;">/</span><span style="color: #000000;">pow</span><span style="color: #0000FF;">)*</span><span style="color: #000000;">10</span> <span style="color: #0000FF;">+</span> <span style="color: #7060A8;">remainder</span><span style="color: #0000FF;">(</span><span style="color: #000000;">j</span><span style="color: #0000FF;">,</span><span style="color: #000000;">10</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">remainder</span><span style="color: #0000FF;">(</span><span style="color: #000000;">j</span><span style="color: #0000FF;">,</span><span style="color: #000000;">fl</span><span style="color: #0000FF;">)==</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%d "</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">count</span> <span style="color: #0000FF;">-=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000000;">j</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">>=</span><span style="color: #000000;">10</span><span style="color: #0000FF;">*</span><span style="color: #000000;">pow</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">pow</span> <span style="color: #0000FF;">*=</span> <span style="color: #000000;">10</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--

View file

@ -0,0 +1,48 @@
To run:
Start up.
Show the gapful numbers at various spots.
Wait for the escape key.
Shut down.
A digit is a number.
To get a digit of a number (last):
Privatize the number.
Divide the number by 10 giving a quotient and a remainder.
Put the remainder into the digit.
To get a digit of a number (first):
Privatize the number.
Loop.
Divide the number by 10 giving a quotient and a remainder.
Put the quotient into the number.
If the number is 0, put the remainder into the digit; exit.
Repeat.
To make a number from the first and last digits of another number:
Get a digit of the other number (first).
Get another digit of the other number (last).
Put the digit times 10 plus the other digit into the number.
To decide if a number is gapful:
Make another number from the first and last digits of the number.
If the number is evenly divisible by the other number, say yes.
Say no.
To show a number of the gapful numbers starting from another number:
Privatize the other number.
Put 0 into a gapful counter.
Loop.
If the other number is gapful, write "" then the other number then " " on the console without advancing; bump the gapful counter.
If the gapful counter is the number, break.
Bump the other number.
Repeat.
Write "" then the return byte on the console.
To show the gapful numbers at various spots:
Write "30 gapful numbers starting at 100:" on the console.
Show 30 of the gapful numbers starting from 100.
Write "15 gapful numbers starting at 1000000:" on the console.
Show 15 of the gapful numbers starting from 1000000.
Write "10 gapful numbers starting at 1000000000:" on the console.
Show 10 of the gapful numbers starting from 1000000000.

View file

@ -0,0 +1,43 @@
function Get-FirstDigit {
param ( [int] $Number )
[int]$Number.ToString().Substring(0,1)
}
function Get-LastDigit {
param ( [int] $Number )
$Number % 10
}
function Get-BookendNumber {
param ( [Int] $Number )
10 * (Get-FirstDigit $Number) + (Get-LastDigit $Number)
}
function Test-Gapful {
param ( [Int] $Number )
100 -lt $Number -and 0 -eq $Number % (Get-BookendNumber $Number)
}
function Find-Gapfuls {
param ( [Int] $Start, [Int] $Count )
$result = @()
While ($result.Count -lt $Count) {
If (Test-Gapful $Start) {
$result += @($Start)
}
$Start += 1
}
return $result
}
function Search-Range {
param ( [Int] $Start, [Int] $Count )
Write-Output "The first $Count gapful numbers >= $($Start):"
Write-Output( (Find-Gapfuls $Start $Count) -join ",")
Write-Output ""
}
Search-Range 1 30
Search-Range 1000000 15
Search-Range 1000000000 10

View file

@ -0,0 +1,30 @@
Procedure.b isGapNum(n.i)
n1.i=n%10
n2.i=Val(Left(Str(n),1))
If n%(n2*10+n1)=0
ProcedureReturn #True
Else
ProcedureReturn #False
EndIf
EndProcedure
Procedure PutGapNum(start.i,rep.i,lfi.i=10)
n.i=start
While rep
If isGapNum(n)
Print(Str(n)+" ")
rep-1
If rep%lfi=0 : PrintN("") : EndIf
EndIf
n+1
Wend
EndProcedure
OpenConsole()
PrintN("First 30 gapful numbers ≥ 100:")
PutGapNum(100,30)
PrintN(~"\nFirst 15 gapful numbers ≥ 1,000,000:")
PutGapNum(1000000,15,5)
PrintN(~"\nFirst 10 gapful numbers ≥ 1,000,000,000:")
PutGapNum(1000000000,10,5)
Input()

View file

@ -0,0 +1,6 @@
from itertools import islice, count
for start, n in [(100, 30), (1_000_000, 15), (1_000_000_000, 10)]:
print(f"\nFirst {n} gapful numbers from {start:_}")
print(list(islice(( x for x in count(start)
if (x % (int(str(x)[0]) * 10 + (x % 10)) == 0) )
, n)))

View file

@ -0,0 +1,31 @@
[ [ [] swap
[ 10 /mod
rot join swap
dup 0 = until ]
drop ] ] is digits ( n --> [ )
[ dup 100 < iff
[ drop false ] done
dup digits
dup 0 peek 10 *
swap -1 peek +
mod 0 = ] is gapful ( n --> b )
[ swap dup temp put
say "First "
echo
say " gapful numbers from "
dup echo cr
[] swap
[ dup gapful if
[ tuck join swap ]
1+
over size
temp share = until ]
drop
witheach [ echo sp ]
cr cr ] is task ( n n --> )
30 100 task
15 1000000 task
10 1000000000 task

View file

@ -0,0 +1,18 @@
/*REXX program computes and displays a series of gapful numbers starting at some number.*/
numeric digits 20 /*ensure enough decimal digits gapfuls.*/
parse arg gapfuls /*obtain optional arguments from the CL*/
if gapfuls='' then gapfuls= 30 25@7123 15@1000000 10@1000000000 /*assume defaults.*/
do until gapfuls=''; parse var gapfuls stuff gapfuls; call gapful stuff
end /*until*/
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
gapful: procedure; parse arg n "@" sp; if sp=='' then sp= 100 /*get args; use default.*/
say center(' 'n " gapful numbers starting at: " sp' ', 125, "")
$=; #= 0 /*initialize the $ list.*/
do j=sp until #==n /*SP: starting point. */
parse var j a 2 '' -1 b /*get 1st and last digit*/
if j // (a||b) \== 0 then iterate /*perform ÷ into J. */
#= # + 1; $= $ j /*bump #; append ──► $ */
end /*j*/
say strip($); say; return

View file

@ -0,0 +1,7 @@
use Lingua::EN::Numbers;
for (1e2, 30, 1e6, 15, 1e9, 10, 7123, 25)».Int -> $start, $count {
put "\nFirst $count gapful numbers starting at {comma $start}:\n" ~
<Sir Lord Duke King>.pick ~ ": ", ~
($start..*).grep( { $_ %% .comb[0, *-1].join } )[^$count];
}

View file

@ -0,0 +1,47 @@
nr = 0
gapful1 = 99
gapful2 = 999999
gapful3 = 999999999
limit1 = 30
limit2 = 15
limit3 = 10
see "First 30 gapful numbers >= 100:" + nl
while nr < limit1
gapful1 = gapful1 + 1
gap1 = left((string(gapful1)),1)
gap2 = right((string(gapful1)),1)
gap = number(gap1 +gap2)
if gapful1 % gap = 0
nr = nr + 1
see "" + nr + ". " + gapful1 + nl
ok
end
see nl
see "First 15 gapful numbers >= 1000000:" + nl
nr = 0
while nr < limit2
gapful2 = gapful2 + 1
gap1 = left((string(gapful2)),1)
gap2 = right((string(gapful2)),1)
gap = number(gap1 +gap2)
if (nr < limit2) and gapful2 % gap = 0
nr = nr + 1
see "" + nr + ". " + gapful2 + nl
ok
end
see nl
see "First 10 gapful numbers >= 1000000000:" + nl
nr = 0
while nr < limit3
gapful3 = gapful3 + 1
gap1 = left((string(gapful3)),1)
gap2 = right((string(gapful3)),1)
gap = number(gap1 +gap2)
if (nr < limit2) and gapful3 % gap = 0
nr = nr + 1
see "" + nr + ". " + gapful3 + nl
ok
end

View file

@ -0,0 +1,13 @@
class Integer
def gapful?
a = digits
self % (a.last*10 + a.first) == 0
end
end
specs = {100 => 30, 1_000_000 => 15, 1_000_000_000 => 10, 7123 => 25}
specs.each do |start, num|
puts "first #{num} gapful numbers >= #{start}:"
p (start..).lazy.select(&:gapful?).take(num).to_a
end

View file

@ -0,0 +1,34 @@
/*
This code is an implementation of gapful numbers in SQL ORACLE 19c
p_start -- start point
p_count -- total number to be found
*/
with
function gapful_numbers(p_start in integer, p_count in integer) return varchar2 is
v_start integer := p_start;
v_count integer := 0;
v_res varchar2(32767);
begin
v_res := 'First '||p_count||' gapful numbers starting from '||p_start||': ';
-- main cycle
while true loop
if mod(v_start,to_number(substr(v_start,1,1)||substr(v_start,-1))) = 0 then
v_res := v_res || v_start;
v_count := v_count + 1;
exit when v_count = p_count;
v_res := v_res || ', ';
end if;
v_start := v_start + 1;
end loop;
--
return v_res;
--
end;
--Test
select gapful_numbers(100,30) as res from dual
union all
select gapful_numbers(1000000,15) as res from dual
union all
select gapful_numbers(1000000000,10) as res from dual;
/

View file

@ -0,0 +1,19 @@
(define (first-digit n) (string->number (string (string-ref (number->string n) 0))))
(define (last-digit n) (modulo n 10))
(define (bookend-number n) (+ (* 10 (first-digit n)) (last-digit n)))
(define (gapful? n) (and (>= n 100) (zero? (modulo n (bookend-number n)))))
(define (gapfuls-in-range start size)
(let ((found 0) (result '()))
(do ((n start (+ n 1))) ((>= found size) (reverse result))
(if (gapful? n)
(begin (set! result (cons n result)) (set! found (+ found 1)))))))
(define (report-range range)
(apply (lambda (start size)
(newline)
(display "The first ")(display size)(display " gapful numbers >= ")
(display start)(display ":")(newline)
(display (gapfuls-in-range start size))(newline)) range))
(map report-range '((100 30) (1000000 15) (1000000000 10)))

View file

@ -0,0 +1,16 @@
func is_gapful(n, base=10) {
n.is_div(base*floor(n / base**n.ilog(base)) + n%base)
}
var task = [
"(Required) The first %s gapful numbers (>= %s)", 30, 1e2, 10,
"(Required) The first %s gapful numbers (>= %s)", 15, 1e6, 10,
"(Required) The first %s gapful numbers (>= %s)", 10, 1e9, 10,
"(Extra) The first %s gapful numbers (>= %s)", 10, 987654321, 10,
"(Extra) The first %s gapful numbers (>= %s)", 10, 987654321, 12,
]
task.each_slice(4, {|title, n, from, b|
say sprintf("\n#{title} for base #{b}:", n, from.commify)
say (from..Inf -> lazy.grep{ is_gapful(_,b) }.first(n).join(' '))
})

View file

@ -0,0 +1,18 @@
func isGapful(n: Int) -> Bool {
guard n > 100 else {
return true
}
let asString = String(n)
let div = Int("\(asString.first!)\(asString.last!)")!
return n % div == 0
}
let first30 = (100...).lazy.filter(isGapful).prefix(30)
let mil = (1_000_000...).lazy.filter(isGapful).prefix(15)
let bil = (1_000_000_000...).lazy.filter(isGapful).prefix(15)
print("First 30 gapful numbers: \(Array(first30))")
print("First 15 >= 1,000,000: \(Array(mil))")
print("First 15 >= 1,000,000,000: \(Array(bil))")

View file

@ -0,0 +1,30 @@
proc ungap n {
if {[string length $n] < 3} {
return $n
}
return [string index $n 0][string index $n end]
}
proc gapful n {
return [expr {0 == ($n % [ungap $n])}]
}
## --> list of gapful numbers >= n
proc GFlist {count n} {
set r {}
while {[llength $r] < $count} {
if {[gapful $n]} {
lappend r $n
}
incr n
}
return $r
}
proc show {count n} {
puts "The first $count gapful >= $n: [GFlist $count $n]"
}
show 30 100
show 15 1000000
show 10 1000000000

View file

@ -0,0 +1,43 @@
first-digit() {
printf '%s\n' "${1:0:1}"
}
last-digit() {
printf '%s\n' $(( $1 % 10 ))
}
bookend-number() {
printf '%s%s\n' "$(first-digit "$@")" "$(last-digit "$@")"
}
is-gapful() {
(( $1 >= 100 && $1 % $(bookend-number "$1") == 0 ))
}
gapfuls-in-range() {
local gapfuls=()
local -i i found
for (( i=$1, found=0; found < $2; ++i )); do
if is-gapful "$i"; then
if (( found )); then
printf ' ';
fi
printf '%s' "$i"
(( found++ ))
fi
done
printf '\n'
}
report-ranges() {
local range
local -i start size
for range; do
IFS=, read start size <<<"$range"
printf 'The first %d gapful numbers >= %d:\n' "$size" "$start"
gapfuls-in-range "$start" "$size"
printf '\n'
done
}
report-ranges 1,30 1000000,15 1000000000,10

View file

@ -0,0 +1,37 @@
fn commatize(n u64) string {
mut s := n.str()
le := s.len
for i := le - 3; i >= 1; i -= 3 {
s = '${s[0..i]},$s[i..]'
}
return s
}
fn main() {
starts := [u64(1e2), u64(1e6), u64(1e7), u64(1e9), u64(7123)]
counts := [30, 15, 15, 10, 25]
for i in 0..starts.len {
mut count := 0
mut j := starts[i]
mut pow := u64(100)
for {
if j < pow*10 {
break
}
pow *= 10
}
println("First ${counts[i]} gapful numbers starting at ${commatize(starts[i])}:")
for count < counts[i] {
fl := (j/pow)*10 + (j % 10)
if j%fl == 0 {
print("$j ")
count++
}
j++
if j >= 10*pow {
pow *= 10
}
}
println("\n")
}
}

View file

@ -0,0 +1,44 @@
Module Module1
Function FirstNum(n As Integer) As Integer
REM Divide by ten until the leading digit remains.
While n >= 10
n /= 10
End While
Return n
End Function
Function LastNum(n As Integer) As Integer
REM Modulo gives you the last digit.
Return n Mod 10
End Function
Sub FindGap(n As Integer, gaps As Integer)
Dim count = 0
While count < gaps
Dim i = FirstNum(n) * 10 + LastNum(n)
REM Modulo with our new integer and output the result.
If n Mod i = 0 Then
Console.Write("{0} ", n)
count += 1
End If
n += 1
End While
Console.WriteLine()
Console.WriteLine()
End Sub
Sub Main()
Console.WriteLine("The first 30 gapful numbers are: ")
FindGap(100, 30)
Console.WriteLine("The first 15 gapful numbers > 1,000,000 are: ")
FindGap(1000000, 15)
Console.WriteLine("The first 10 gapful numbers > 1,000,000,000 are: ")
FindGap(1000000000, 10)
End Sub
End Module

View file

@ -0,0 +1,24 @@
import "/fmt" for Fmt
var starts = [1e2, 1e6, 1e7, 1e9, 7123]
var counts = [30, 15, 15, 10, 25]
for (i in 0...starts.count) {
var count = 0
var j = starts[i]
var pow = 100
while (true) {
if (j < pow * 10) break
pow = pow * 10
}
System.print("First %(counts[i]) gapful numbers starting at %(Fmt.dc(0, starts[i]))")
while (count < counts[i]) {
var fl = (j/pow).floor*10 + (j % 10)
if (j%fl == 0) {
System.write("%(j) ")
count = count + 1
}
j = j + 1
if (j >= 10*pow) pow = pow * 10
}
System.print("\n")
}

View file

@ -0,0 +1,24 @@
func isgapful(n:number):boolean{
set s:string = tostring(n);
set d = toint(`{s::at(0)}{s::at(?s-1)}`);
send (n%d)==0
}
func findGapfulNumbers(start,amount){
set gapful=[];
set ind = start;
while(true){
if(isgapful(ind)){
gapful::insert(ind);
}
ind++;
if((?gapful)>=amount){
stop;
}
}
log(`First {amount} gapful ints at {start}: {gapful::join(", ")}`);
}
findGapfulNumbers(100,30);
findGapfulNumbers(1000000,15);
findGapfulNumbers(1000000000,15);

View file

@ -0,0 +1,31 @@
func Gapful(N0); \Return 'true' if gapful number
int N0, N, First, Last;
[N:= N0;
N:= N/10;
Last:= rem(0);
repeat N:= N/10;
First:= rem(0);
until N = 0;
N:= First*10 + Last;
return rem(N0/N) = 0;
];
proc ShowGap(Start, Limit); \Display gapful numbers
int Start, Limit, Count, N;
[Text(0, "First "); IntOut(0, Limit); Text(0, " gapful numbers starting from ");
IntOut(0, Start); Text(0, ":^m^j");
Count:= 0; N:= Start;
loop [if Gapful(N) then
[IntOut(0, N); ChOut(0, ^ );
Count:= Count+1;
if Count >= Limit then quit;
];
N:= N+1;
];
CrLf(0);
];
[ShowGap(100, 30);
ShowGap(1_000_000, 15);
ShowGap(1_000_000_000, 10);
]

View file

@ -0,0 +1,27 @@
sub is_gapful(n)
m = n
l = mod(n, 10)
while (m >= 10)
m = int(m / 10)
wend
return (m * 10) + l
end sub
sub muestra_gapful(n, gaps)
inc = 0
print "Primeros ", gaps, " numeros gapful >= ", n
while inc < gaps
if mod(n, is_gapful(n)) = 0 then
print " " , n ,
inc = inc + 1
end if
n = n + 1
wend
print chr$(10)
end sub
muestra_gapful(100, 30)
muestra_gapful(1000000, 15)
muestra_gapful(1000000000, 10)
muestra_gapful(7123,25)
end

View file

@ -0,0 +1,4 @@
fcn gapfulW(start){ //--> iterator
[start..].tweak(
fcn(n){ if(n % (10*n.toString()[0] + n%10)) Void.Skip else n })
}

View file

@ -0,0 +1,5 @@
foreach n,z in
( T( T(100, 30), T(1_000_000, 15), T(1_000_000_000, 10), T(7_123,25) )){
println("First %d gapful numbers starting at %,d:".fmt(z,n));
gapfulW(n).walk(z).concat(", ").println("\n");
}