Nimber arithmetic: Difference between revisions
Content added Content deleted
Thundergnat (talk | contribs) m (→{{header|Raku}}: Twiddles; also demo operations on > 64 bit numbers) |
m (Rust - reformatted with rustfmt) |
||
Line 813: | Line 813: | ||
{{trans|FreeBASIC}} |
{{trans|FreeBASIC}} |
||
<lang rust>// highest power of 2 that divides a given number |
<lang rust>// highest power of 2 that divides a given number |
||
fn hpo2(n |
fn hpo2(n: u32) -> u32 { |
||
n & (0xFFFFFFFF - n + 1) |
n & (0xFFFFFFFF - n + 1) |
||
} |
} |
||
// base 2 logarithm of the highest power of 2 dividing a given number |
// base 2 logarithm of the highest power of 2 dividing a given number |
||
fn lhpo2(n |
fn lhpo2(n: u32) -> u32 { |
||
let mut q |
let mut q: u32 = 0; |
||
let mut m |
let mut m: u32 = hpo2(n); |
||
while m % 2 == 0 { |
while m % 2 == 0 { |
||
m >>= 1; |
m >>= 1; |
||
Line 829: | Line 829: | ||
// nim-sum of two numbers |
// nim-sum of two numbers |
||
fn nimsum(x |
fn nimsum(x: u32, y: u32) -> u32 { |
||
x ^ y |
x ^ y |
||
} |
} |
||
// nim-product of two numbers |
// nim-product of two numbers |
||
fn nimprod(x |
fn nimprod(x: u32, y: u32) -> u32 { |
||
if x < 2 || y < 2 { |
if x < 2 || y < 2 { |
||
return x * y; |
return x * y; |
||
} |
} |
||
let mut h |
let mut h: u32 = hpo2(x); |
||
if x > h { |
if x > h { |
||
return nimprod(h, y) ^ nimprod(x ^ h, y); |
return nimprod(h, y) ^ nimprod(x ^ h, y); |
||
Line 845: | Line 845: | ||
return nimprod(y, x); |
return nimprod(y, x); |
||
} |
} |
||
let xp |
let xp: u32 = lhpo2(x); |
||
let yp |
let yp: u32 = lhpo2(y); |
||
let comp |
let comp: u32 = xp & yp; |
||
if comp == 0 { |
if comp == 0 { |
||
return x * y; |
return x * y; |
||
Line 855: | Line 855: | ||
} |
} |
||
fn print_table(n |
fn print_table(n: u32, op: char, func: fn(u32, u32) -> u32) { |
||
print!(" {} |", op); |
print!(" {} |", op); |
||
for a in 0..=n { |
for a in 0..=n { |
||
Line 878: | Line 878: | ||
println!(); |
println!(); |
||
print_table(15, '*', nimprod); |
print_table(15, '*', nimprod); |
||
let a |
let a: u32 = 21508; |
||
let b |
let b: u32 = 42689; |
||
println!("\n{} + {} = {}", a, b, nimsum(a, b)); |
println!("\n{} + {} = {}", a, b, nimsum(a, b)); |
||
println!("{} * {} = {}", a, b, nimprod(a, b)); |
println!("{} * {} = {}", a, b, nimprod(a, b)); |