duangu9997 2015-12-06 23:47
浏览 43
已采纳

紧凑地写入10的幂作为常数

I'm reading the recently released The Go Programming Language, and it's been a joy so far (with Brian Kernighan being one of the authors, I wouldn't expect anything other than excellence anyway).

I've came across the following exercise on chapter 3:

Exercise 3.13 Write const declarations for KB, MB, up through YB as compactly as you can.

(NOTE: in this context, KB, MB, etc, denote powers of 1000)

This is preceded by a section where iota is introduced as a useful constants generator mechanism; in particular, the previous paragraph shows a nice and compact way to define the powers of 1024 as constants:

const (
    _ = 1 << (10 * iota)
    KiB
    MiB
    GiB
    TiB
    PiB
    EiB
    ZiB
    YiB
)

The authors further mention this regarding powers of 10:

The iota mechanism has its limits. For example, it's not possible to generate the more familiar powers of 1000 (KB, MB, and so son) because there is no exponentiation operator.

I'm struggling with this exercise because it looks like the expected solution is something a little more elaborate than simply spelling out the powers of 1000 by hand (especially since it appears after iota is introduced). I feel like there is some clever way to do this that uses iota in a subtle way combined with something else.

I thought about finding a systematic way to subtract the "excess" amount out of each of the powers of 1024 to get the powers of 1000, but it led me to nowhere. Then I looked at the binary representations to try and infer a general pattern where iota could be useful, but again, I got nothing.

I really can't see how one would generate powers of 1000 out of a single incrementing value (iota) without an exponentiation operator.

Any ideas?

  • 写回答

2条回答 默认 最新

  • doufei2328 2015-12-07 00:39
    关注

    I would say that this is impossible because what you want is to represent a function 10^(3i) where i is a positive integer as some function f(i), where f is a compositive function of your elementary go functions (+, -, /, *).

    It was possible for 2^(10i) only because go introduced another elementary function integer exponentiation. So if 1 << y would allow y being float, you would be able to modify your code to use 1 << (log2(10) * 3 * i). This would worked because this is equivalent to solving 10^(3i) = 2^y. Taking log2 of both sides y = log2(10) * 3 * i.

    But sadly enough bitwise shift is an integer operation.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 网络科学导论,网络控制
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)