abhi_yo's blog

By abhi_yo, history, 6 months ago, In English

A Small Number Theory Challenge

Hello everyone,

I came across an interesting observation and wanted to hear different approaches and ideas from the community.

Problem

You are given two integers A and B (**B ≠ 0**).

Consider the decimal representation of the fraction A / B.

Your task is to determine whether the decimal representation will terminate after a finite number of digits or continue forever.

Output:

  • YES if the decimal representation terminates.
  • NO otherwise.

Examples

Example 1

Input:

3 8

Output:

YES

Explanation:

3 / 8 = 0.375

The decimal representation terminates.


Example 2

Input:

1 3

Output:

NO

Explanation:

1 / 3 = 0.333333...

The decimal representation never terminates.


Example 3

Input:

14 40

Output:

YES

Explanation:

14 / 40 = 0.35

The decimal representation terminates.


Example 4

Input:

5 14

Output:

NO

Explanation:

5 / 14 = 0.357142857142...

The decimal representation does not terminate.

Constraints

1 ≤ |A|, |B| ≤ 10^18

Discussion

I'm interested in seeing different observations, proofs, and solutions.

  • What property of A and B determines the answer?
  • Is there a mathematical characterization of such fractions?
  • Can it be solved efficiently for very large values?
  • Are there multiple approaches?

Feel free to share your reasoning, proofs, optimizations, or code snippets.

  • Vote: I like it
  • -16
  • Vote: I do not like it

»
6 months ago, hide # |
 
Vote: I like it 0 Vote: I do not like it
b /= gcd(a, b);
while (b % 2 == 0) b /= 2;
while (b % 5 == 0) b /= 5;
cout << (b == 1 ? "it terminates lmao" : "it doesn't XD XD XD") << endl;
»
6 months ago, hide # |
 
Vote: I like it 0 Vote: I do not like it

Yes there is actually a mathematical method to find whether a fraction is terminating or not.

Simplify the fraction A/B completely first. After simplification, look at the prime factors of B. If B only contains the prime factors 2, 5 or a combination of both, the fraction terminates. If it contains any other prime factor, it does not terminate.