Home > Java > javaTutorial > How to Fix the 'Integer Number Too Large' Error When Finding Prime Factors?

How to Fix the 'Integer Number Too Large' Error When Finding Prime Factors?

Patricia Arquette
Release: 2024-11-09 19:27:02
Original
837 people have browsed it

How to Fix the

Overcoming "Integer Number Too Large" Error for 600851475143

The code snippet provided attempts to find the largest prime factor of the number 600851475143. However, upon running the code, it encounters an "Integer number too large" error. This error arises because 600851475143 exceeds the maximum value that can be represented by a 32-bit integer, which is the type used in the code.

To resolve this issue and find the largest prime factor of 600851475143, the code must use a data type capable of representing larger values. This can be achieved by modifying the type of i to long, a 64-bit integer.

Here's the corrected code:

public class Three {
    public static void main(String[] args) {
        Three obj = new Three();
        obj.function(600851475143L);
    }

    private Long function(long i) {
        Stack<Long> stack = new Stack<Long>();

        for (long j = 2; j <= i; j++) {
            if (i % j == 0) {
                stack.push(j);
            }
        }
        return stack.pop();
    }
}
Copy after login

By writing the literal 600851475143 as 600851475143L, it is explicitly represented as a 64-bit integer. This allows the code to accurately find and return the largest prime factor of the given number.

The above is the detailed content of How to Fix the 'Integer Number Too Large' Error When Finding Prime Factors?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template