Question

Consider the following code:

public static void main(String[] args){
        int target = 99999;
        revised(target);

    long total = 0;
    for(int x = 0; x <= target; x++){
        if(x % 3 == 0 || x % 5 == 0)
        total+=x;
    }
    System.out.println("Method B: " + total);
}

private static double findSum(int target, int divisor){
        int upperBound = target/divisor;
        return divisor*(upperBound+1)*upperBound*.5;
}

private static void revised(int target){
        double sumOne = findSum(target, 3);
        double sumTwo = findSum(target, 5);
        double sumThree = findSum(target, 15);
        System.out.printf("Method A: %.0f  \n", sumOne + sumTwo - sumThree);
}

Project Euler #1 Problem: Print the sum of integers that are divisible by 3 or 5.

The following code is correct when target is 9, 99, 999, 9999; however, fails when the target variable is set to 99999. The answer generated by the revised function does not yield the same result as the brute force method located in the main function. I do not believe this is due to an overflow of the double type.

Can someone please explain why the revised function fails when given large numbers but yields the same results (as the brute force method) when given smaller numbers?

Was it helpful?

Solution

Just Use Same DataType every where Double

public static void main(String[] args){
            int target = 99999;
            revised(target);
    }

private static double findSum(double target, double divisor){
            double upperBound = target/divisor;
            System.out.println("|"+upperBound+"|"+target+"|"+divisor);
            return divisor*(upperBound+1)*upperBound*.5;
    }

private static void revised(double target){
            double sumOne = findSum(target, 3);
            double sumTwo = findSum(target, 5);
            double sumThree = findSum(target, 15);
            System.out.printf("%.0f  \n", sumOne + sumTwo - sumThree);
            System.out.println("|"+sumOne+"|"+sumTwo+"|"+sumThree);
    }

This problem occurs, when datatype is convert round is performed

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top