First power of 2 that has leading decimal digits of 12: Difference between revisions

m
Added Easylang
(add freebasic)
m (Added Easylang)
 
(25 intermediate revisions by 17 users not shown)
Line 35:
::*   display the results here, on this page.
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">F p(=l, n, pwr = 2)
l = Int(abs(l))
V digitcount = floor(log(l, 10))
V log10pwr = log(pwr, 10)
V (raised, found) = (-1, 0)
L found < n
raised++
V firstdigits = floor(10 ^ (fract(log10pwr * raised) + digitcount))
I firstdigits == l
found++
R raised
 
L(l, n) [(12, 1), (12, 2), (123, 45), (123, 12345), (123, 678910)]
print(‘p(’l‘, ’n‘) = ’p(l, n))</syntaxhighlight>
 
{{out}}
<pre>
p(12, 1) = 7
p(12, 2) = 80
p(123, 45) = 12710
p(123, 12345) = 3510491
p(123, 678910) = 193060223
</pre>
 
=={{header|ALGOL 68}}==
As wih the Go second sample, computes approximate integer values for the powers of 2.
<br>Requires LONG INT to be at least 64 bits (as in Algol 68G).
<langsyntaxhighlight lang="algol68"># find values of p( L, n ) where p( L, n ) is the nth-smallest j such that #
# the decimal representation of 2^j starts with the digits of L #
BEGIN
Line 88 ⟶ 115:
print p( 123, 12345 );
print p( 123, 678910 )
END</langsyntaxhighlight>
{{out}}
<pre>
Line 97 ⟶ 124:
p(123, 678910) = 193,060,223
</pre>
 
=={{header|BASIC256}}==
<syntaxhighlight lang="basic256">global FAC
FAC = 0.30102999566398119521373889472449302677
 
print p(12, 1)
print p(12, 2)
print p(123, 45)
print p(123, 12345)
print p(123, 678910)
end
 
function p(L, n)
cont = 0 : j = 0
LS = string(L)
while cont < n
j += 1
x = FAC * j
if x < length(LS) then continue while
y = 10^(x-int(x))
y *= 10^length(LS)
digits = string(y)
if left(digits,length(LS)) = LS then cont += 1
end while
return j
end function</syntaxhighlight>
{{out}}
<pre>Same as FreeBASIC entry.</pre>
 
=={{header|C}}==
{{trans|Java}}
<langsyntaxhighlight lang="c">#include <math.h>
#include <stdio.h>
 
Line 136 ⟶ 191:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>p(12, 1) = 7
Line 148 ⟶ 203:
{{trans|Go}}
{{trans|Pascal}}
<langsyntaxhighlight lang="cpp">// a mini chrestomathy solution
 
#include <string>
Line 235 ⟶ 290:
doOne("go integer", gi);
doOne("pascal alternative", pa);
}</langsyntaxhighlight>
{{out}}Exeution times from Tio.run, language: C++ (clang) or C++ (gcc), compiler flags: -O3 -std=c++17
<pre>java simple version:
Line 277 ⟶ 332:
Took 0.082407 seconds</pre>
 
=={{header|C sharp|C#}}==
{{trans|C++}}
<langsyntaxhighlight cpplang="csharp">// a mini chrestomathy solution
 
using System;
Line 362 ⟶ 417:
doOne("pascal alternative", pa);
}
}</langsyntaxhighlight>
{{out}}
Results on the core i7-7700 @ 3.6Ghz.
Line 394 ⟶ 449:
=={{header|D}}==
{{trans|C}}
<langsyntaxhighlight lang="d">import std.math;
import std.stdio;
 
Line 428 ⟶ 483:
runTest(123, 12345);
runTest(123, 678910);
}</langsyntaxhighlight>
{{out}}
<pre>p(12, 1) = 7
Line 435 ⟶ 490:
p(123, 12345) = 3510491
p(123, 678910) = 193060223</pre>
=={{header|Delphi}}==
See [https://rosettacode.org/wiki/First_power_of_2_that_has_leading_decimal_digits_of_12#Pascal Pascal].
 
=={{header|EasyLang}}==
{{trans|Java}}
<syntaxhighlight>
func p l n .
log = log10 2
factor = 1
loop = l
while loop > 10
factor *= 10
loop = loop div 10
.
while n > 0
test += 1
val = floor (factor * pow 10 (test * log mod 1))
if val = l
n -= 1
.
.
return test
.
proc test l n . .
print "p(" & l & ", " & n & ") = " & p l n
.
test 12 1
test 12 2
test 123 45
test 123 12345
test 123 678910
</syntaxhighlight>
{{out}}
<pre>
p(12, 1) = 7
p(12, 2) = 80
p(123, 45) = 12710
p(123, 12345) = 3510491
p(123, 678910) = 193060223
</pre>
 
=={{header|F_Sharp|F#}}==
<syntaxhighlight lang="fsharp">
// First power of 2 that has specified leading decimal digits. Nigel Galloway: March 14th., 2021
let fG n g=let fN l=let l=10.0**(l-floor l) in l>=n && l<g in let f=log10 2.0 in seq{1..0x0FFFFFFF}|>Seq.filter(float>>(*)f>>fN)
printfn "p(23,1)->%d" (int(Seq.item 0 (fG 2.3 2.4)))
printfn "p(99,1)->%d" (int(Seq.item 0 (fG 9.9 10.0)))
printfn "p(12,1)->%d" (int(Seq.item 0 (fG 1.2 1.3)))
printfn "p(12,2)->%d" (int(Seq.item 1 (fG 1.2 1.3)))
printfn "p(123,45)->%d" (int(Seq.item 44 (fG 1.23 1.24)))
printfn "p(123,12345)->%d" (int(Seq.item 12344 (fG 1.23 1.24)))
printfn "p(123,678910)->%d" (int(Seq.item 678909 (fG 1.23 1.24)))
</syntaxhighlight>
{{out}}
<pre>
p(23,1)->61
p(99,1)->93
p(12,1)->7
p(12,2)->80
p(123,45)->12710
p(123,12345)->3510491
p(123,678910)->193060223
Real: 00:00:10.140
</pre>
 
=={{header|Factor}}==
Line 440 ⟶ 559:
{{trans|Pascal}}
{{works with|Factor|0.99 2019-10-06}}
<langsyntaxhighlight lang="factor">USING: formatting fry generalizations kernel literals math
math.functions math.parser sequences tools.time ;
 
Line 461 ⟶ 580:
123 678910
[ 2dup p "%d %d p = %d\n" printf ] 2 5 mnapply
] time</langsyntaxhighlight>
{{out}}
<pre>
Line 473 ⟶ 592:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">#define FAC 0.30102999566398119521373889472449302677
 
function p( L as uinteger, n as uinteger ) as uinteger
Line 495 ⟶ 614:
print p(123, 45)
print p(123, 12345)
print p(123, 678910)</langsyntaxhighlight>
{{out}}
<pre>
Line 503 ⟶ 622:
3510491
193060223</pre>
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
local fn p( l as NSInteger, n as NSInteger ) as NSInteger
NSInteger test = 0, factor = 1, loop = l
double logv = log(2.0) / log(10.0)
while ( loop > 10 )
factor *= 10
loop /= 10
wend
while ( n > 0 )
NSInteger v
test++
v = (NSInteger)( factor * fn pow( 10.0, fn fmod( test * logv, 1 ) ) )
if ( v == l ) then n--
wend
end fn = test
 
void local fn RunTest( l as NSInteger, n as NSInteger )
printf @"fn p( %d, %d ) = %d", l, n, fn p( l, n )
end fn
 
fn RunTest( 12, 1 )
fn RunTest( 12, 2 )
fn RunTest( 123, 45 )
fn RunTest( 123, 12345 )
fn RunTest( 123, 678910 )
 
HandleEvents
</syntaxhighlight>
{{output}}
<pre>
fn p( 12, 1 ) = 7
fn p( 12, 2 ) = 80
fn p( 123, 45 ) = 12710
fn p( 123, 12345 ) = 3510491
fn p( 123, 678910 ) = 193060223
</pre>
 
=={{header|Gambas}}==
{{trans|FreeBASIC}}
<syntaxhighlight lang="vbnet">Public Sub Main()
Print p(12, 1)
Print p(12, 2)
Print p(123, 45)
Print p(123, 12345)
Print p(123, 678910)
End
 
Function p(L As Integer, n As Integer) As Integer
 
Dim FAC As Float = 0.30102999566398119521373889472449302677
Dim count As Integer, j As Integer = 0
Dim x As Float, y As Float
Dim digits As String, LS As String = Str(L)
 
While count < n
j += 1
x = FAC * j
If x < Len(LS) Then Continue
y = 10 ^ (x - CInt(x))
y *= 10 ^ Len(LS)
digits = Str(y)
If Left(digits, Len(LS)) = LS Then count += 1
Wend
Return j
 
End Function</syntaxhighlight>
 
=={{header|Go}}==
{{trans|Pascal}}
<langsyntaxhighlight lang="go">package main
 
import (
Line 549 ⟶ 740:
}
fmt.Printf("\nTook %s\n", time.Since(start))
}</langsyntaxhighlight>
 
{{out}}
Line 563 ⟶ 754:
 
or, translating the alternative Pascal version as well, for good measure:
<langsyntaxhighlight lang="go">package main
 
import (
Line 629 ⟶ 820:
}
fmt.Printf("\nTook %s\n", time.Since(start))
}</langsyntaxhighlight>
 
{{out}}
Line 644 ⟶ 835:
=={{header|Haskell}}==
{{trans|Python}}
<langsyntaxhighlight lang="haskell">import Control.Monad (guard)
import Text.Printf (printf)
 
Line 661 ⟶ 852:
main :: IO ()
main = mapM_ (\(l, n) -> printf "p(%d, %d) = %d\n" l n (p l n))
[(12, 1), (12, 2), (123, 45), (123, 12345), (123, 678910)]</langsyntaxhighlight>
 
Which, desugaring a little from Control.Monad (guard) and the do syntax, could also be rewritten as:
<langsyntaxhighlight lang="haskell">import Text.Printf (printf)
 
p :: Int -> Int -> Int
p l n = ([-1 ..] >>= f) !! pred n
where
digitCount = floor $ logBase 10 (fromIntegral l :: Float)
floor $
logBase 10 (fromIntegral l :: Float)
log10pwr = logBase 10 2
f raised = [ds | l == ds]
[ ds
| ds == l ]
where
ds =
floor $
10 ** 10
** ( snd
(snd (properFraction $ log10pwr * realToFrac raised) + realToFrac digitCount)
( properFraction $
log10pwr * realToFrac raised
)
+ realToFrac digitCount
)
 
main :: IO ()
Line 684 ⟶ 880:
mapM_
(\(l, n) -> printf "p(%d, %d) = %d\n" l n (p l n))
[ (12, 1),
[(12, 1), (12, 2), (123, 45), (123, 12345), (123, 678910)]</lang>
(12, 2),
(123, 45),
(123, 12345),
(123, 678910)
]</syntaxhighlight>
 
{{out}}
Line 695 ⟶ 896:
=={{header|J}}==
Modeled on the python version. Depending on the part of speech defined, the variable names x, y, u, v, m, and n can have special meaning within explicit code. They are defined by the arguments. In the fonts I usually use, lower case "l" is troublesome as well.
<syntaxhighlight lang="j">
<lang J>
p=: adverb define
:
Line 712 ⟶ 913:
raised
)
</syntaxhighlight>
</lang>
 
<pre>
Line 724 ⟶ 925:
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">
public class FirstPowerOfTwo {
 
Line 759 ⟶ 960:
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 769 ⟶ 970:
</pre>
 
=={{header|jq}}==
This solution uses unbounded-precision integers represented as arrays
of decimal digits beginning with the least significant digit,
e.g. [1,2,3] represents 321.
 
To speed up the computation, a variable limit on the number of significant digits
is used. Details can be seen in the implementation of p/2; for example,
for p(123, 678910) the number of significant digits starts off at (10 + 30) = 40
and gradually tapers off to 10.
 
(Starting with (8+28) and tapering off to 8 is insufficient.)
<syntaxhighlight lang="jq">def normalize_base($base):
def n:
if length == 1 and .[0] < $base then .[0]
else .[0] % $base,
((.[0] / $base|floor) as $carry
|.[1:]
| .[0] += $carry
| n )
end;
n;
def integers_as_arrays_times($n; $base):
map(. * $n)
| [normalize_base($base)];
 
 
def p($L; $n):
# @assert($L > 0 and $n > 0)
($L|tostring|explode|reverse|map(. - 48)) as $digits # "0" is 48
| ($digits|length) as $ndigits
| (2*(2+($n|log|floor))) as $extra
| { m: $n,
i: 0,
keep: ( 2*(2+$ndigits) + $extra),
p: [1] # reverse-array representation of 1
}
| until(.m == 0;
.i += 1
| .p |= integers_as_arrays_times(2; 10)
| .p = .p[ -(.keep) :]
| if (.p[-$ndigits:]) == $digits
then
| .m += -1 | .keep -= ($extra/$n)
else . end )
| .i;
## The task
[[12, 1], [12, 2], [123, 45], [123, 12345], [123, 678910]][]
| "With L = \(.[0]) and n = \(.[1]), p(L, n) = \( p(.[0]; .[1]))"
</syntaxhighlight>
{{out}}
As for Julia.
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">function p(L, n)
@assert(L > 0 && n > 0)
places, logof2, nfound = trunc(log(10, L)), log(10, 2), 0
Line 783 ⟶ 1,037:
println("With L = $L and n = $n, p(L, n) = ", p(L, n))
end
</langsyntaxhighlight>{{out}}
<pre>
With L = 12 and n = 1, p(L, n) = 7
Line 794 ⟶ 1,048:
===Faster version===
{{trans|Go}}
<langsyntaxhighlight lang="julia">using Formatting, BenchmarkTools
 
function p(L, n)
Line 834 ⟶ 1,088:
testpLn(true)
@btime testpLn(false)
</langsyntaxhighlight>{{out}}
<pre>
With L = 12 and n = 1, p(L, n) = 7
Line 846 ⟶ 1,100:
=={{header|Kotlin}}==
{{trans|Java}}
<langsyntaxhighlight lang="scala">import kotlin.math.ln
import kotlin.math.pow
 
Line 880 ⟶ 1,134:
}
return test
}</langsyntaxhighlight>
{{out}}
<pre>p(12, 1) = 7
Line 887 ⟶ 1,141:
p(123, 12345) = 3,510,491
p(123, 678910) = 193,060,223</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Without compilation arbitrary precision will be used, and the algorithm will be slow, compiled is much faster:
<syntaxhighlight lang="mathematica">f = Compile[{{ll, _Integer}, {n, _Integer}},
Module[{l, digitcount, log10power, raised, found, firstdigits, pwr = 2},
l = Abs[ll];
digitcount = Floor[Log[10, l]];
log10power = Log[10, pwr];
raised = -1;
found = 0;
While[found < n,
raised++;
firstdigits = Floor[10^(FractionalPart[log10power raised] + digitcount)];
If[firstdigits == l,
found += 1;
]
];
Return[raised]
]
];
f[12, 1]
f[12, 2]
f[123, 45]
f[123, 12345]
f[123, 678910]</syntaxhighlight>
{{out}}
<pre>7
80
12710
3510491
193060223</pre>
 
=={{header|Nim}}==
{{trans|Pascal}}
This is a translation to Nim of the very efficient Pascal alternative algorithm, with minor adjustments.
<syntaxhighlight lang="nim">import math, strformat
 
const
Lfloat64 = pow(2.0, 64)
Log10_2_64 = int(Lfloat64 * log10(2.0))
 
#---------------------------------------------------------------------------------------------------
 
func ordinal(n: int): string =
case n
of 1: "1st"
of 2: "2nd"
of 3: "3rd"
else: $n & "th"
 
#---------------------------------------------------------------------------------------------------
 
proc findExp(number, countLimit: int) =
 
var i = number
var digits = 1
while i >= 10:
digits *= 10
i = i div 10
 
var lmtLower, lmtUpper: uint64
var log10num = log10((number + 1) / digits)
if log10num >= 0.5:
lmtUpper = if (number + 1) / digits < 10: uint(log10Num * (Lfloat64 * 0.5)) * 2 + uint(log10Num * 2)
else: 0
log10Num = log10(number / digits)
lmtLower = uint(log10Num * (Lfloat64 * 0.5)) * 2 + uint(log10Num * 2)
else:
lmtUpper = uint(log10Num * Lfloat64)
lmtLower = uint(log10(number / digits) * Lfloat64)
 
var count = 0
var frac64 = 0u64
var p = 0
if lmtUpper != 0:
while true:
inc p
inc frac64, Log10_2_64
if frac64 in lmtLower..lmtUpper:
inc count
if count >= countLimit:
break
else:
# Searching for "999...".
while true:
inc p
inc frac64, Log10_2_64
if frac64 >= lmtLower:
inc count
if count >= countLimit:
break
 
echo fmt"""The {ordinal(count)} occurrence of 2 raised to a power""" &
fmt""" whose product starts with "{number}" is {p}"""
 
#———————————————————————————————————————————————————————————————————————————————————————————————————
 
findExp(12, 1)
findExp(12, 2)
 
findExp(123, 45)
findExp(123, 12345)
findExp(123, 678910)</syntaxhighlight>
 
{{out}}
Processor: Core I5 8250U
 
Compilation command: <code>nim c -d:danger --passC:-flto leading12.nim</code>
 
Time: about 110 ms
 
 
<pre>The 1st occurrence of 2 raised to a power whose product starts with "12" is 7
The 2nd occurrence of 2 raised to a power whose product starts with "12" is 80
The 45th occurrence of 2 raised to a power whose product starts with "123" is 12710
The 12345th occurrence of 2 raised to a power whose product starts with "123" is 3510491
The 678910th occurrence of 2 raised to a power whose product starts with "123" is 193060223</pre>
 
=={{header|Pascal}}==
Line 893 ⟶ 1,264:
<b>0<= base ** frac(x) < base </b> thats 1 digit before the comma<Br>
Only the first digits are needed.So I think, the accuracy is sufficient, because the results are the same :-)
<langsyntaxhighlight lang="pascal">program Power2FirstDigits;
 
uses
sysutils,strUtils;
strUtils;
 
const
{$IFDEF FPC}
ld10= ln(2)/ln(10);// thats 1/log2(10)
{$MODE DELPHI}
 
ld10 :double = ln(2)/ln(10);// thats 1/log2(10)
function FindExp(CntLmt,Number:NativeUint):NativeUint;
{$ELSE}
ld10 = 0.30102999566398119521373889472449;
 
function Numb2USA(const S: string): string;
var
i,cnt,DgtShift NA: NativeUIntInteger;
begin
i := Length(S);
//calc how many Digits needed
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}
 
function FindExp(CntLmt, Number: NativeUint): NativeUint;
var
i, cnt, DgtShift: NativeUInt;
begin
//calc how many Digits needed
i := Number;
DgtShift := 1;
while i >= 10 do
Beginbegin
DgtShift* := DgtShift * 10;
i := i div 10;
end;
Line 919 ⟶ 1,317:
// x= i*ld10 -> 2^I = 10^x
// 10^frac(x) -> [0..10[ = exp(ln(10)*frac(i*lD10))
IFif truncTrunc(DgtShift * exp(ln(10) * frac(i * lD10))) = Number then
Beginbegin
inc(cnt);
IFif cnt >= CntLmt then
BREAK;
end;
until false;
write('The ', Numb2USA(IntToStr(cnt)), 'th occurrence of 2 raised to a power');
write(' whose product starts with "', Numb2USA(IntToStr(numberNumber)));
writeln('" is ', Numb2USA(IntToStr(i)));
FindExp := i;
end;
 
begin
Begin
FindExp(1, 12);
FindExp(2, 12);
 
FindExp(45, 123);
FindExp(12345, 123);
FindExp(678910, 123);
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 955 ⟶ 1,353:
Logarithm (Ln(Number/Digits)/ln(10) <= frac(i*lD10) < ln((Number+1)/Digits)/ln(10) => no exp<BR>
 
<langsyntaxhighlight lang="pascal">program Power2Digits;
uses
sysutils,strUtils;
Line 1,042 ⟶ 1,440:
 
FindExp(1,99);
end.</langsyntaxhighlight>
{{out}}
<pre>The 1th occurrence of 2 raised to a power whose product starts with "12" is 7
Line 1,058 ⟶ 1,456:
=={{header|Perl}}==
{{trans|Raku}}
<langsyntaxhighlight lang="perl">use strict;
use warnings;
use feature 'say';
Line 1,120 ⟶ 1,518:
printf "%-15s %9s power of two (2^n) that starts with %5s is at n = %s\n", "p($prefix, $nth):",
comma($nth) . ordinal_digit($nth), "'$prefix'", comma p($prefix, $nth);
}</langsyntaxhighlight>
{{out}}
<pre>p(12, 1): 1st power of two (2^n) that starts with '12' is at n = 7
Line 1,129 ⟶ 1,527:
 
=={{header|Phix}}==
{{libheader|Phix/mpfr}}
<lang Phix>function p(integer L, n)
<!--<syntaxhighlight lang="phix">(phixonline)-->
atom logof2 = log10(2)
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
integer places = trunc(log10(L)),
<span style="color: #008080;">function</span> <span style="color: #000000;">p</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">L</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
nfound = 0, i = 1
<span style="color: #004080;">atom</span> <span style="color: #000000;">logof2</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">log10</span><span style="color: #0000FF;">(</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)</span>
while true do
<span style="color: #004080;">integer</span> <span style="color: #000000;">places</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">trunc</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">log10</span><span style="color: #0000FF;">(</span><span style="color: #000000;">L</span><span style="color: #0000FF;">)),</span>
atom a = i * logof2,
<span style="color: #000000;">nfound</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">i</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
b = trunc(power(10,a-trunc(a)+places))
<span style="color: #008080;">while</span> <span style="color: #004600;">true</span> <span style="color: #008080;">do</span>
if L == b then
<span style="color: #004080;">atom</span> <span style="color: #000000;">a</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">i</span> <span style="color: #0000FF;">*</span> <span style="color: #000000;">logof2</span><span style="color: #0000FF;">,</span>
nfound += 1
<span style="color: #000000;">b</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">trunc</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">power</span><span style="color: #0000FF;">(</span><span style="color: #000000;">10</span><span style="color: #0000FF;">,</span><span style="color: #000000;">a</span><span style="color: #0000FF;">-</span><span style="color: #7060A8;">trunc</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">)+</span><span style="color: #000000;">places</span><span style="color: #0000FF;">))</span>
if nfound == n then exit end if
<span style="color: #008080;">if</span> <span style="color: #000000;">L</span> <span style="color: #0000FF;">==</span> <span style="color: #000000;">b</span> <span style="color: #008080;">then</span>
end if
<span style="color: #000000;">nfound</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
i += 1
<span style="color: #008080;">if</span> <span style="color: #000000;">nfound</span> <span style="color: #0000FF;">==</span> <span style="color: #000000;">n</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end while
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
return i
<span style="color: #000000;">i</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
end function
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">i</span>
constant tests = {{12, 1}, {12, 2}, {123, 45}, {123, 12345}, {123, 678910}}
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
include ordinal.e
include mpfr.e
<span style="color: #008080;">constant</span> <span style="color: #000000;">tests</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{{</span><span style="color: #000000;">12</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">},</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">12</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">},</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">123</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">45</span><span style="color: #0000FF;">},</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">123</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">12345</span><span style="color: #0000FF;">},</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">123</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">678910</span><span style="color: #0000FF;">}}</span>
mpz z = mpz_init()
<span style="color: #008080;">include</span> <span style="color: #7060A8;">ordinal</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
for i=1 to length(tests) do
<span style="color: #008080;">include</span> <span style="color: #004080;">mpfr</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
integer {L,n} = tests[i], pln = p(L,n)
<span style="color: #004080;">mpz</span> <span style="color: #000000;">z</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpz_init</span><span style="color: #0000FF;">()</span>
mpz_ui_pow_ui(z,2,pln)
<span style="color: #004080;">atom</span> <span style="color: #000000;">t0</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">time</span><span style="color: #0000FF;">()</span>
integer digits = mpz_sizeinbase(z,10)
<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;">tests</span><span style="color: #0000FF;">)-(</span><span style="color: #000000;">2</span><span style="color: #0000FF;">*(</span><span style="color: #7060A8;">platform</span><span style="color: #0000FF;">()=</span><span style="color: #004600;">JS</span><span style="color: #0000FF;">))</span> <span style="color: #008080;">do</span>
string st = iff(digits>2e6?sprintf("%,d digits",digits):
<span style="color: #004080;">integer</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">L</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">tests</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span> <span style="color: #000000;">pln</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">p</span><span style="color: #0000FF;">(</span><span style="color: #000000;">L</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
shorten(mpz_get_str(z),"digits",5))
<span style="color: #7060A8;">mpz_ui_pow_ui</span><span style="color: #0000FF;">(</span><span style="color: #000000;">z</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">pln</span><span style="color: #0000FF;">)</span>
printf(1,"The %d%s power of 2 that starts with %d is %d [i.e. %s]\n",{n,ord(n),L,pln,st})
<span style="color: #004080;">integer</span> <span style="color: #000000;">digits</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpz_sizeinbase</span><span style="color: #0000FF;">(</span><span style="color: #000000;">z</span><span style="color: #0000FF;">,</span><span style="color: #000000;">10</span><span style="color: #0000FF;">)</span>
end for</lang>
<span style="color: #004080;">string</span> <span style="color: #000000;">st</span> <span style="color: #0000FF;">=</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">digits</span><span style="color: #0000FF;">></span><span style="color: #000000;">2e6</span><span style="color: #0000FF;">?</span><span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"%,d digits"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">digits</span><span style="color: #0000FF;">):</span>
<span style="color: #7060A8;">shorten</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">mpz_get_str</span><span style="color: #0000FF;">(</span><span style="color: #000000;">z</span><span style="color: #0000FF;">),</span><span style="color: #008000;">"digits"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">5</span><span style="color: #0000FF;">))</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;">"The %d%s power of 2 that starts with %d is %d [i.e. %s]\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">ord</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">),</span><span style="color: #000000;">L</span><span style="color: #0000FF;">,</span><span style="color: #000000;">pln</span><span style="color: #0000FF;">,</span><span style="color: #000000;">st</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">elapsed</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">time</span><span style="color: #0000FF;">()-</span><span style="color: #000000;">t0</span><span style="color: #0000FF;">)</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 1,165 ⟶ 1,569:
The 678910th power of 2 that starts with 123 is 193060223 [i.e. 58,116,919 digits]
</pre>
<small>(The last two tests are simply too much for pwa/p2js)</small>
 
=={{header|Python}}==
Using logs, as seen first in the Pascal example.
 
<langsyntaxhighlight lang="python">from math import log, modf, floor
 
def p(l, n, pwr=2):
Line 1,186 ⟶ 1,591:
if __name__ == '__main__':
for l, n in [(12, 1), (12, 2), (123, 45), (123, 12345), (123, 678910)]:
print(f"p({l}, {n}) =", p(l, n))</langsyntaxhighlight>
 
{{out}}
Line 1,194 ⟶ 1,599:
p(123, 12345) = 3510491
p(123, 678910) = 193060223</pre>
 
=={{header|Racket}}==
 
{{trans|Pascal}}
 
First implementation is an untyped, naive revision of the Pascal algorithm.
But there is a lot of casting between the exact integers an floats. As well as runtime type checking.
 
Then there is the typed racket version, which is stricter about the use of types
(although, I'm not super happy at the algorithm counting using floating-point integers... but it's faster)
 
Compare and contrast...
 
===Untyped Racket===
 
<syntaxhighlight lang="racket">#lang racket
(define (fract-part f)
(- f (truncate f)))
 
(define ln10 (log 10))
(define ln2/ln10 (/ (log 2) ln10))
(define (inexact-p-test L)
(let ((digit-shift (let loop ((L (quotient L 10)) (shift 1))
(if (zero? L) shift (loop (quotient L 10) (* 10 shift))))))
(λ (p) (= L (truncate (* digit-shift (exp (* ln10 (fract-part (* p ln2/ln10))))))))))
 
(define (p L n)
(let ((test? (inexact-p-test L)))
(let loop ((j 1) (n (sub1 n)))
(cond [(not (test? j)) (loop (add1 j) n)]
[(zero? n) j]
[else (loop (add1 j) (sub1 n))]))))
 
(module+ main
(define (report-p L n)
(time (printf "p(~a, ~a) = ~a~%" L n (p L n))))
(report-p 12 1)
(report-p 12 2)
(report-p 123 45)
(report-p 123 12345)
(report-p 123 678910))</syntaxhighlight>
 
{{out}}
 
<pre>p(12, 1) = 7
cpu time: 1 real time: 1 gc time: 0
p(12, 2) = 80
cpu time: 0 real time: 0 gc time: 0
p(123, 45) = 12710
cpu time: 5 real time: 5 gc time: 0
p(123, 12345) = 3510491
cpu time: 439 real time: 442 gc time: 23
p(123, 678910) = 193060223
cpu time: 27268 real time: 27354 gc time: 194</pre>
 
===Typed Racket===
 
<syntaxhighlight lang="racket">#lang typed/racket
 
(: fract-part (-> Float Float))
(: ln10 Positive-Float)
(: ln2/ln10 Positive-Float)
(: p (-> Positive-Index Positive-Index Positive-Integer))
 
(define (fract-part f)
(- f (truncate f)))
 
(define ln10 (cast (log 10) Positive-Float))
(define ln2/ln10 (cast (/ (log 2) ln10) Positive-Float))
(define (inexact-p-test [L : Positive-Index])
(let ((digit-shift : Nonnegative-Float
(let loop ((L (quotient L 10)) (shift : Nonnegative-Float 1.))
(if (zero? L) shift (loop (quotient L 10) (* 10. shift)))))
(l (exact->inexact L)))
(: f (-> Nonnegative-Float Boolean))
(define (f p) (= l (truncate (* digit-shift (exp (* ln10 (fract-part (* p ln2/ln10))))))))
f))
 
(define (p L n)
(let ((test? (inexact-p-test L)))
(let loop : Positive-Integer ((j : Positive-Float 1.) (n : Index (sub1 n)))
(cond [(not (test? j)) (loop (add1 j) n)]
[(zero? n) (assert (exact-round j) positive?)]
[else (loop (add1 j) (sub1 n))]))))
 
(module+ main
(: report-p (-> Positive-Index Positive-Index Void))
(define (report-p L n)
(time (printf "p(~a, ~a) = ~a~%" L n (p L n))))
(report-p 12 1)
(report-p 12 2)
(report-p 123 45)
(report-p 123 12345)
(report-p 123 678910))
</syntaxhighlight>
 
{{out}}
<pre>p(12, 1) = 7
cpu time: 1 real time: 1 gc time: 0
p(12, 2) = 80
cpu time: 0 real time: 0 gc time: 0
p(123, 45) = 12710
cpu time: 5 real time: 5 gc time: 0
p(123, 12345) = 3510491
cpu time: 237 real time: 231 gc time: 31
p(123, 678910) = 193060223
cpu time: 10761 real time: 10794 gc time: 17</pre>
 
=={{header|Raku}}==
Line 1,200 ⟶ 1,716:
Uses logs similar to Go and Pascal entries. Takes advantage of patterns in the powers to cut out a bunch of calculations.
 
<syntaxhighlight lang="raku" perl6line>use Lingua::EN::Numbers;
 
constant $ln2ln10 = log(2) / log(10);
Line 1,235 ⟶ 1,751:
printf "%-15s %9s power of two (2^n) that starts with %5s is at n = %s\n", "p($prefix, $nth):",
comma($nth) ~ ordinal-digit($nth).substr(*-2), "'$prefix'", comma p($prefix, $nth);
}</langsyntaxhighlight>
{{out}}
<pre>p(12, 1): 1st power of two (2^n) that starts with '12' is at n = 7
Line 1,244 ⟶ 1,760:
 
=={{header|REXX}}==
<langsyntaxhighlight lang="rexx">/*REXX program computes powers of two whose leading decimal digits are "12" (in base 10)*/
parse arg L n b . /*obtain optional arguments from the CL*/
if L=='' | L=="," then L= 12 /*Not specified? Then use the default.*/
Line 1,272 ⟶ 1,788:
/*──────────────────────────────────────────────────────────────────────────────────────*/
commas: arg _; do c=length(_)-3 to 1 by -3; _= insert(',', _, c); end; return _
th: arg _; return _ || word('th st nd rd', 1 +_//10 * (_//100 % 10\==1) * (_//10 <4))</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the inputs of: &nbsp; &nbsp; <tt> 12 &nbsp; 1 </tt>}}
<pre>
Line 1,292 ⟶ 1,808:
<pre>
The 678910th occurrence of 2 raised to a power whose product starts with "123' is 193,060,223.
</pre>
=={{header|RPL}}==
{{trans|C}}
{{works with|HP|48}}
The <code>6 RND</code> sequence is necessary on calculators, which do the math in simple precision. It can be removed when executing the program on a double precision emulator.
« SWAP DUP XPON ALOG 2 LOG → digits factor log2
« 0
'''WHILE''' OVER 0 > '''REPEAT'''
1 +
DUP log2 * FP ALOG 6 RND factor * IP
'''IF''' digits == '''THEN''' SWAP 1 - SWAP '''END'''
'''END'''
SWAP DROP
» » '<span style="color:blue">P</span>' STO
 
12 1 <span style="color:blue">P</span>
12 2 <span style="color:blue">P</span>
123 45 <span style="color:blue">P</span>
{{out}}
<pre>
3: 7
2: 80
1: 12710
</pre>
The last result needs 29 minutes on a basic HP-48SX.
 
=={{header|Ruby}}==
{{trans|C}}
<syntaxhighlight lang="ruby">def p(l, n)
test = 0
logv = Math.log(2.0) / Math.log(10.0)
factor = 1
loopv = l
while loopv > 10 do
factor = factor * 10
loopv = loopv / 10
end
while n > 0 do
test = test + 1
val = (factor * (10.0 ** ((test * logv).modulo(1.0)))).floor
if val == l then
n = n - 1
end
end
return test
end
 
def runTest(l, n)
print "P(%d, %d) = %d\n" % [l, n, p(l, n)]
end
 
runTest(12, 1)
runTest(12, 2)
runTest(123, 45)
runTest(123, 12345)
runTest(123, 678910)</syntaxhighlight>
{{out}}
<pre>P(12, 1) = 7
P(12, 2) = 80
P(123, 45) = 12710
P(123, 12345) = 3510491
P(123, 678910) = 193060223</pre>
 
=={{header|Rust}}==
<syntaxhighlight lang="rust">fn power_of_two(l: isize, n: isize) -> isize {
let mut test: isize = 0;
let log: f64 = 2.0_f64.ln() / 10.0_f64.ln();
let mut factor: isize = 1;
let mut looop = l;
let mut nn = n;
while looop > 10 {
factor *= 10;
looop /= 10;
}
 
while nn > 0 {
test = test + 1;
let val: isize = (factor as f64 * 10.0_f64.powf(test as f64 * log % 1.0)) as isize;
 
if val == l {
nn = nn - 1;
}
}
 
test
}
 
fn run_test(l: isize, n: isize) {
println!("p({}, {}) = {}", l, n, power_of_two(l, n));
}
 
fn main() {
run_test(12, 1);
run_test(12, 2);
run_test(123, 45);
run_test(123, 12345);
run_test(123, 678910);
}
</syntaxhighlight>
{{out}}
<pre>
p(12, 1) = 7
p(12, 2) = 80
p(123, 45) = 12710
p(123, 12345) = 3510491
p(123, 678910) = 193060223
</pre>
 
=={{header|Scala}}==
{{trans|Java}}
<langsyntaxhighlight lang="scala">object FirstPowerOfTwo {
def p(l: Int, n: Int): Int = {
var n2 = n
Line 1,328 ⟶ 1,950:
runTest(123, 678910)
}
}</langsyntaxhighlight>
{{out}}
<pre>p(12, 1) = 7
Line 1,337 ⟶ 1,959:
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func farey_approximations(r, callback) {
 
var (a1 = r.int, b1 = 1)
Line 1,399 ⟶ 2,021:
for a,b in (tests) {
say "p(#{a}, #{b}) = #{p(a,b)}"
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,417 ⟶ 2,039:
===Slower Version===
 
<langsyntaxhighlight lang="swift">let ld10 = log(2.0) / log(10.0)
 
func p(L: Int, n: Int) -> Int {
Line 1,455 ⟶ 2,077:
for (l, n) in cases {
print("p(\(l), \(n)) = \(p(L: l, n: n))")
}</langsyntaxhighlight>
 
{{out}}
Line 1,467 ⟶ 2,089:
===Faster Version===
 
<langsyntaxhighlight lang="swift">import Foundation
 
func p2(L: Int, n: Int) -> Int {
Line 1,534 ⟶ 2,156:
for (l, n) in cases {
print("p(\(l), \(n)) = \(p2(L: l, n: n))")
}</langsyntaxhighlight>
 
{{out}}
Line 1,541 ⟶ 2,163:
 
=={{header|Visual Basic .NET}}==
<langsyntaxhighlight lang="vbnet">Module Module1
 
Function Func(ByVal l As Integer, ByVal n As Integer) As Long
Line 1,571 ⟶ 2,193:
End Sub
 
End Module</langsyntaxhighlight>
{{out}}
<pre>p( 12, 1) = 60
Line 1,584 ⟶ 2,206:
{{libheader|Wren-fmt}}
{{libheader|Wren-math}}
Just the first version which has turned out to be much quicker than the Go entry (around 3728 seconds on the same machine). Frankly, I've no idea why.
<langsyntaxhighlight ecmascriptlang="wren">import "./fmt" for Fmt
import "./math" for Math
 
var ld10 = Math.ln2 / Math.ln10
Line 1,600 ⟶ 2,222:
i = 0
while (count < n) {
var e = Math.exp(Math.ln10 * (i * ld10).fraction).exp
if ((e * digits).truncate == L) count = count + 1
i = i + 1
Line 1,613 ⟶ 2,235:
}
 
System.print("\nTook %(System.clock - start) seconds.")</langsyntaxhighlight>
 
{{out}}
Line 1,623 ⟶ 2,245:
p(123, 678910) = 193,060,223
 
Took 2716.85138651308 seconds.
</pre>
 
=={{header|Yabasic}}==
<syntaxhighlight lang="yabasic">FAC = 0.30102999566398119521373889472449302677
 
print p(12, 1)
print p(12, 2)
print p(123, 45)
print p(123, 12345)
print p(123, 678910)
end
 
sub p(L, n)
cont = 0 : j = 0
LS$ = str$(L)
while cont < n
j = j + 1
x = FAC * j
//if x < len(LS$) continue while 'sino da error
y = 10^(x-int(x))
y = y * 10^len(LS$)
digits$ = str$(y)
if left$(digits$, len(LS$)) = LS$ cont = cont + 1
end while
return j
end sub</syntaxhighlight>
 
=={{header|zkl}}==
{{trans|Pascal}}
Lots of float are slow so I've restricted the tests.
<langsyntaxhighlight lang="zkl">// float*int --> float and int*float --> int
fcn p(L,nth){ // 2^j = <L><digits>
var [const] ln10=(10.0).log(), ld10=(2.0).log() / ln10;
Line 1,638 ⟶ 2,285:
return(i);
}
}</langsyntaxhighlight>
{{libheader|GMP}} GNU Multiple Precision Arithmetic Library
GMP is just used to give some context on the size of the numbers we
are dealing with.
<langsyntaxhighlight lang="zkl">var [const] BI=Import("zklBigNum"); // libGMP
tests:=T( T(12,1),T(12,2), T(123,45),T(123,12345), );
foreach L,nth in (tests){
Line 1,648 ⟶ 2,295:
println("2^%-10,d is occurance %,d of 2^n == '%d<abc>' (%,d digits)"
.fmt(n,nth,L,BI(2).pow(n).len()));
}</langsyntaxhighlight>
{{out}}
<pre>
2,022

edits