web123456

C++ code determines whether a given number is an ugly number

Question description

Positive integers containing only factors 2, 3, 5 are called ugly numbers. For example, 4, 10, 12 are all ugly numbers, while 7, 23, 111 are not ugly numbers, and the other 1 is not ugly numbers. Please write a function and enter an integer n to determine whether the integer is an ugly number. If so, output True, otherwise output False.

Enter a description

Enter a positive integer n on each line

1 <= n<= 1000000

Output description

For each line of input, output whether it is an ugly number. If yes, output True, otherwise output False

Sample input

4
7
12

Sample output

True
False
True
  1. This algorithm is essentially a process of reducing the entire process of prime factor decomposition using code logic.When the given number num takes the remainder 2, 3, 5 and 0 equal to 0, the factor representing num must include 2, 3, and 5.
  2. Using num divided by 2, 3, 5 can be expressed as decomposing a factor, and so on. When num==1, the factor representing a given number only contains 2, 3, 5. According to the definition, you can know that this number is an ugly number.
#include <iostream>
 using namespace std;

 bool isUgly(int num) {
	 /*When num contains a factor 2, the remaining result must be 0; num/2 is equivalent to decomposing a factor: 2.
	 And so on, when num==1, the factor indicating that the given number only contains 2, 3, and 5. According to the definition, you can know that this number is an ugly number*/
	 While (num % 2 == 0)
		 num /= 2;
	 While (num % 3 == 0)
		 num /= 3;
	 While (num % 5 == 0)
		 num /= 5;
	 return num == 1 ? true : false;
 }

 int main() {
	 int num;
	 /*If you need to enter, you can use an array to save the number entered by the user*/
	 while (true) {
		 cin >> num;
		 if (!num) {
			 break;
		 }
		 cout << (isUgly(num) ? "True" : "False") << "\n";
	 }
	 system("pause");
	 return 0;
 }