Avoiding overflow with large numbers when using Mo

2019-09-02 04:09发布

I began toying with project euler.

I have completed problem #3, but I was only able to complete it by setting my endNumber to 71 * 486847 (manually calculated). When trying to set endNumber = 600851475143 I receive the overflow error.

I even set endNumber as Long, and even Double which I think should be plenty of digits to calculate.

I can't post the whole code here, so I'll post half in hopes someone can show me how to edit it in order to process larger numbers.

Also I noticed that "#" pops up when my code has a very large number like below.

endNumber = 600851475143#
        countFactor = 0

        For i = 2 To endNumber
            If endNumber Mod i = 0 Then 

2条回答
趁早两清
2楼-- · 2019-09-02 04:48

The overflow isn't due to assigning the number 600851475143 to the Double variable it is that the Mod function does not seem to handle numbers longer than Long very well (in fact seemingly not at all).

An alternative can be to use the manual calc for Mod:

endNumber = 600851475143#
        countFactor = 0

        For i = 2 To endNumber
            If endNumber - (Int(endNumber / i) * i) = 0 Then

If you are going to use Mod for large numbers on a regular basis then Chip Pearson's function would be a useful one (which is where I learnt about this subject matter in the first place). It is posted as a problem in Excel but works perfectly in Access.

查看更多
聊天终结者
3楼-- · 2019-09-02 05:13

The highest possible number to work with in a long is: 2.147.483.647
A Double is for decimal purposes, so thats not what you are looking for.

The # that pops up is because a number is to large to be shown inside that cell.

Also I don't know what you want to do with that loop. But that one is going to take a very long while to run.

on this link you can find about handling large numbers: Large Number Arithmetic

Hope that helps

查看更多
登录 后发表回答