Programming challenge “Greatest Odd Divisor” I am trying to solve a programming problem on a coding platform. When I submit the code on the coding platform, it throws a &quot;Time Limit Exceeded&quot; error. Can someone check my solution and help optimize it?


A food delivery company X gets a lot of orders every day. It charges some
commission from the restaurants on these orders. More formally, if an order
value is K, X charges a commission which is the greatest odd divisor of K. You
can assume that an order value will always be an integer. Given an order value
N, and let C(N) be the greatest odd-divisor of N, output the value of C(1) +
C(2) + C(3) + … + C(N).
INPUT : Input will be an integer, N, the order value. 1 &lt;= N &lt;= 10^9
OUTPUT : Single integer which is the answer


import java.util.*;
public class Solution {
    static double GOD(double num)
    {
        if(num%2!=0)
        {
            return num;
        }
        else
        {
            for (double i = num / 2; i &gt; 0 ;i--)
            {
                if (num % i == 0 &amp;&amp; i % 2 != 0)
                {
                    return i;
                }
            }
            return 0;
        }
     }
public static void main(String args[] ) throws Exception {
   
    Scanner sc = new Scanner(System.in);
    double num = sc.nextDouble();
    double sum = 0;
    for(double i = 1; i&lt;=num; i++)
        {
        sum = sum + GOD(i);
    }
    System.out.println((int)sum);
}
}
You should not be using doubles to perform integer arithmetic. Stick to int or long.

This is a brute-force search that follows the instructions very literally.  That is the wrong approach. Similar to Project Euler Problem 3, the fast way to find the largest factor is by finding the smallest factors. Just divide by 2 as many times as possible.

Example:

$$360 = 2^3 \cdot 45$$

The largest odd divisor is therefore 45.