First power of 2 that has leading decimal digits of 12: Difference between revisions
Content deleted Content added
Alextretyak (talk | contribs) |
PascalABC.NET |
||
(12 intermediate revisions by 7 users not shown) | |||
Line 39:
{{trans|Python}}
<
l = Int(abs(l))
V digitcount = floor(log(l, 10))
Line 52:
L(l, n) [(12, 1), (12, 2), (123, 45), (123, 12345), (123, 678910)]
print(‘p(’l‘, ’n‘) = ’p(l, n))</
{{out}}
Line 66:
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).
<
# the decimal representation of 2^j starts with the digits of L #
BEGIN
Line 115:
print p( 123, 12345 );
print p( 123, 678910 )
END</
{{out}}
<pre>
Line 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}}
<
#include <stdio.h>
Line 163 ⟶ 191:
return 0;
}</
{{out}}
<pre>p(12, 1) = 7
Line 175 ⟶ 203:
{{trans|Go}}
{{trans|Pascal}}
<
#include <string>
Line 262 ⟶ 290:
doOne("go integer", gi);
doOne("pascal alternative", pa);
}</
{{out}}Exeution times from Tio.run, language: C++ (clang) or C++ (gcc), compiler flags: -O3 -std=c++17
<pre>java simple version:
Line 304 ⟶ 332:
Took 0.082407 seconds</pre>
=={{header|C sharp|C#}}==
{{trans|C++}}
<
using System;
Line 389 ⟶ 417:
doOne("pascal alternative", pa);
}
}</
{{out}}
Results on the core i7-7700 @ 3.6Ghz.
Line 421 ⟶ 449:
=={{header|D}}==
{{trans|C}}
<
import std.stdio;
Line 455 ⟶ 483:
runTest(123, 12345);
runTest(123, 678910);
}</
{{out}}
<pre>p(12, 1) = 7
Line 464 ⟶ 492:
=={{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 lang=text>
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#}}==
<
// 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)
Line 476 ⟶ 542:
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>
Line 488 ⟶ 554:
Real: 00:00:10.140
</pre>
=={{header|Factor}}==
A translation of the first Pascal example:
{{trans|Pascal}}
{{works with|Factor|0.99 2019-10-06}}
<
math.functions math.parser sequences tools.time ;
Line 513 ⟶ 580:
123 678910
[ 2dup p "%d %d p = %d\n" printf ] 2 5 mnapply
] time</
{{out}}
<pre>
Line 525 ⟶ 592:
=={{header|FreeBASIC}}==
<
function p( L as uinteger, n as uinteger ) as uinteger
Line 547 ⟶ 614:
print p(123, 45)
print p(123, 12345)
print p(123, 678910)</
{{out}}
<pre>
Line 555 ⟶ 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}}
<
import (
Line 601 ⟶ 740:
}
fmt.Printf("\nTook %s\n", time.Since(start))
}</
{{out}}
Line 615 ⟶ 754:
or, translating the alternative Pascal version as well, for good measure:
<
import (
Line 681 ⟶ 820:
}
fmt.Printf("\nTook %s\n", time.Since(start))
}</
{{out}}
Line 696 ⟶ 835:
=={{header|Haskell}}==
{{trans|Python}}
<
import Text.Printf (printf)
Line 713 ⟶ 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)]</
Which, desugaring a little from Control.Monad (guard) and the do syntax, could also be rewritten as:
<
p :: Int -> Int -> Int
Line 746 ⟶ 885:
(123, 12345),
(123, 678910)
]</
{{out}}
Line 757 ⟶ 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">
p=: adverb define
:
Line 774 ⟶ 913:
raised
)
</syntaxhighlight>
<pre>
Line 786 ⟶ 925:
=={{header|Java}}==
<
public class FirstPowerOfTwo {
Line 821 ⟶ 960:
}
</syntaxhighlight>
{{out}}
<pre>
Line 842 ⟶ 981:
(Starting with (8+28) and tapering off to 8 is insufficient.)
<
def n:
if length == 1 and .[0] < $base then .[0]
Line 881 ⟶ 1,020:
[[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}}==
<
@assert(L > 0 && n > 0)
places, logof2, nfound = trunc(log(10, L)), log(10, 2), 0
Line 898 ⟶ 1,037:
println("With L = $L and n = $n, p(L, n) = ", p(L, n))
end
</
<pre>
With L = 12 and n = 1, p(L, n) = 7
Line 909 ⟶ 1,048:
===Faster version===
{{trans|Go}}
<
function p(L, n)
Line 949 ⟶ 1,088:
testpLn(true)
@btime testpLn(false)
</
<pre>
With L = 12 and n = 1, p(L, n) = 7
Line 961 ⟶ 1,100:
=={{header|Kotlin}}==
{{trans|Java}}
<
import kotlin.math.pow
Line 995 ⟶ 1,134:
}
return test
}</
{{out}}
<pre>p(12, 1) = 7
Line 1,005 ⟶ 1,144:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Without compilation arbitrary precision will be used, and the algorithm will be slow, compiled is much faster:
<
Module[{l, digitcount, log10power, raised, found, firstdigits, pwr = 2},
l = Abs[ll];
Line 1,026 ⟶ 1,165:
f[123, 45]
f[123, 12345]
f[123, 678910]</
{{out}}
<pre>7
Line 1,037 ⟶ 1,176:
{{trans|Pascal}}
This is a translation to Nim of the very efficient Pascal alternative algorithm, with minor adjustments.
<
const
Line 1,104 ⟶ 1,243:
findExp(123, 45)
findExp(123, 12345)
findExp(123, 678910)</
{{out}}
Line 1,125 ⟶ 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 :-)
<
uses
Line 1,198 ⟶ 1,337:
FindExp(12345, 123);
FindExp(678910, 123);
end.</
{{out}}
<pre>
Line 1,214 ⟶ 1,353:
Logarithm (Ln(Number/Digits)/ln(10) <= frac(i*lD10) < ln((Number+1)/Digits)/ln(10) => no exp<BR>
<
uses
sysutils,strUtils;
Line 1,301 ⟶ 1,440:
FindExp(1,99);
end.</
{{out}}
<pre>The 1th occurrence of 2 raised to a power whose product starts with "12" is 7
Line 1,314 ⟶ 1,453:
//32Bit
real 0m0,389s</pre>
=={{header|PascalABC.NET}}==
<syntaxhighlight lang="delphi">
function p(L,n: integer): integer;
begin
var logof2 := log10(2);
var places := trunc(log10(L));
var nfound := 0;
var i := 1;
while True do
begin
var a := i * logof2;
var b := trunc(power(10,a-trunc(a)+places));
if L = b then
begin
nfound += 1;
if nfound = n then break
end;
i += 1;
end;
Result := i;
end;
begin
foreach var (L,n) in Arr((12, 1), (12, 2), (123, 45), (123, 12345), (123, 678910)) do
Println($'p({n},{L}) = {p(n, L)}')
end.
</syntaxhighlight>
{{out}}
<pre>
p(1,12) = 40
p(2,12) = 58
p(45,123) = 12868
p(12345,123) = 3398841
p(678910,123) = 188197328
</pre>
=={{header|Perl}}==
{{trans|Raku}}
<
use warnings;
use feature 'say';
Line 1,379 ⟶ 1,554:
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);
}</
{{out}}
<pre>p(12, 1): 1st power of two (2^n) that starts with '12' is at n = 7
Line 1,389 ⟶ 1,564:
=={{header|Phix}}==
{{libheader|Phix/mpfr}}
<!--<
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<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>
Line 1,421 ⟶ 1,596:
<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>
<!--</
{{out}}
<pre>
Line 1,435 ⟶ 1,610:
Using logs, as seen first in the Pascal example.
<
def p(l, n, pwr=2):
Line 1,452 ⟶ 1,627:
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))</
{{out}}
Line 1,475 ⟶ 1,650:
===Untyped Racket===
<
(define (fract-part f)
(- f (truncate f)))
Line 1,502 ⟶ 1,677:
(report-p 123 45)
(report-p 123 12345)
(report-p 123 678910))</
{{out}}
Line 1,519 ⟶ 1,694:
===Typed Racket===
<
(: fract-part (-> Float Float))
Line 1,558 ⟶ 1,733:
(report-p 123 12345)
(report-p 123 678910))
</syntaxhighlight>
{{out}}
Line 1,577 ⟶ 1,752:
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"
constant $ln2ln10 = log(2) / log(10);
Line 1,612 ⟶ 1,787:
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);
}</
{{out}}
<pre>p(12, 1): 1st power of two (2^n) that starts with '12' is at n = 7
Line 1,621 ⟶ 1,796:
=={{header|REXX}}==
<
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,649 ⟶ 1,824:
/*──────────────────────────────────────────────────────────────────────────────────────*/
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))</
{{out|output|text= when using the inputs of: <tt> 12 1 </tt>}}
<pre>
Line 1,670 ⟶ 1,845:
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}}
<
test = 0
logv = Math.log(2.0) / Math.log(10.0)
Line 1,699 ⟶ 1,899:
runTest(123, 45)
runTest(123, 12345)
runTest(123, 678910)</
{{out}}
<pre>P(12, 1) = 7
Line 1,708 ⟶ 1,908:
=={{header|Rust}}==
<
let mut test: isize = 0;
let log: f64 = 2.0_f64.ln() / 10.0_f64.ln();
Line 1,742 ⟶ 1,942:
run_test(123, 678910);
}
</syntaxhighlight>
{{out}}
<pre>
Line 1,754 ⟶ 1,954:
=={{header|Scala}}==
{{trans|Java}}
<
def p(l: Int, n: Int): Int = {
var n2 = n
Line 1,786 ⟶ 1,986:
runTest(123, 678910)
}
}</
{{out}}
<pre>p(12, 1) = 7
Line 1,795 ⟶ 1,995:
=={{header|Sidef}}==
<
var (a1 = r.int, b1 = 1)
Line 1,857 ⟶ 2,057:
for a,b in (tests) {
say "p(#{a}, #{b}) = #{p(a,b)}"
}</
{{out}}
<pre>
Line 1,875 ⟶ 2,075:
===Slower Version===
<
func p(L: Int, n: Int) -> Int {
Line 1,913 ⟶ 2,113:
for (l, n) in cases {
print("p(\(l), \(n)) = \(p(L: l, n: n))")
}</
{{out}}
Line 1,925 ⟶ 2,125:
===Faster Version===
<
func p2(L: Int, n: Int) -> Int {
Line 1,992 ⟶ 2,192:
for (l, n) in cases {
print("p(\(l), \(n)) = \(p2(L: l, n: n))")
}</
{{out}}
Line 1,999 ⟶ 2,199:
=={{header|Visual Basic .NET}}==
<
Function Func(ByVal l As Integer, ByVal n As Integer) As Long
Line 2,029 ⟶ 2,229:
End Sub
End Module</
{{out}}
<pre>p( 12, 1) = 60
Line 2,042 ⟶ 2,242:
{{libheader|Wren-fmt}}
{{libheader|Wren-math}}
Just the first version which has turned out to be much quicker than the Go entry (around
<
import "./math" for Math
var ld10 = Math.ln2 / Math.ln10
Line 2,058 ⟶ 2,258:
i = 0
while (count < n) {
var e =
if ((e * digits).truncate == L) count = count + 1
i = i + 1
Line 2,071 ⟶ 2,271:
}
System.print("\nTook %(System.clock - start) seconds.")</
{{out}}
Line 2,081 ⟶ 2,281:
p(123, 678910) = 193,060,223
Took
</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.
<
fcn p(L,nth){ // 2^j = <L><digits>
var [const] ln10=(10.0).log(), ld10=(2.0).log() / ln10;
Line 2,096 ⟶ 2,321:
return(i);
}
}</
{{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.
<
tests:=T( T(12,1),T(12,2), T(123,45),T(123,12345), );
foreach L,nth in (tests){
Line 2,106 ⟶ 2,331:
println("2^%-10,d is occurance %,d of 2^n == '%d<abc>' (%,d digits)"
.fmt(n,nth,L,BI(2).pow(n).len()));
}</
{{out}}
<pre>
|