Alice loves candies, so she went into a candy shop. Now the shopkeeper sells candies in packets and all packets contain an odd number of candies (1, 3, 5, 7.....). Alice wants exactly candies but she also loves patterns so she decided to buy candies only if the number of candies in the packets is consecutive and distinct (means she cannot buy the same candy packet more than once) and the sum of all the candies in those packets is exactly .
Alice has an infinite amount of money and the shopkeeper also has infinite amount candy packets, so Alice wonders how many different sets of candy packets she can buy.
Find the number of different sets of candy packets that Alice can buy.
Example:
Input: n=45
Output: 3
Approach
Java
public class AliceAndCandies {public static void main(String args[]) throws Exception {long N = 45;long ans = 0;for (long i = 1; i * i <= N; i++) {if (N % i == 0) {long a = i, b = N / i;if ((a % 2 == 0 && b % 2 == 0) || (a % 2 == b % 2)) {if (validPair(a, b) == true) {ans++;}if (i * i != N && validPair(b, a) == true) {ans++;}}}}System.out.println(ans);}public static boolean validPair(long a, long b) {long n2 = (a + b) / 2;long n1 = (a - b) / 2;if (n1 >= 0 && n2 >= 0 && n2 >= n1) {return true;}return false;}}
No comments:
Post a Comment