C#,愚弄数(Hoax Number)的计算方法与源代码

C#,愚弄数(Hoax Number)的计算方法与源代码_第1张图片

一、愚弄数(Hoax Number)

愚弄数(Hoax Number)是一种组合数字, 其数字总和等于其不同质因数的数字总和。
注:1不被视为质数, 因此它不包含在不同质因数的总和中。
有些愚弄数(Hoax Number)数字也是史密斯数字(Smith Number)。

运行效果:

C#,愚弄数(Hoax Number)的计算方法与源代码_第2张图片

二、愚弄数的计算方法

1、首先生成数字 x 的所有唯一质数;
2、如果 x 不是质数, 请找到在步骤1中获得的因子的数字总和;
3、找到数字 x 的总和;
4、检查在步骤2和3中获得的总和是否相等;
5、如果总和相等, 则 x 是一个hoax数字。

三、算法步骤

1、输入要检查的数字n。
2、如果n大于1,则迭代循环。质数从2开始,所以一开始,循环从2开始,即i=2。
3、如果n%i=0,则在ArrayList中添加i,并返回n=n/i以进行进一步迭代。
4、要检查不同的质数因子,请检查ArrayList是否包含任何重复的元素,并在另一个ArrayList中添加不同的元素。
5、现在,要找到ArrayList中的数字之和,请迭代循环,直到达到ArrayList的大小。
6、求数组中每个数字的和。
7、打印质数因子的位数之和。
8、现在,找到输入的数字的数字之和,然后打印。
9、最后,检查从第7步和第8步获得的总和,如果它们相等,则该数字是一个愚弄数,否则它不是一个愚弄数。

源代码

using System;
using System.Collections;
using System.Collections.Generic;

namespace Legalsoft.Truffer.Algorithm
{
	/// 
	/// C# code to check if a number is a hoax number or not.
	/// This code is contributed by Manish Shaw (manishshaw1)
	/// 
	public static class HoaxNumber
	{
		/// 
		/// 计算 x 的全部不同质因子
		/// Function to find distinct 
		/// prime factors of given number n
		/// 
		/// 
		/// 
		public static List PrimeFactors(int x)
		{
			List res = new List();
			if ((x % 2) == 0)
			{
				while ((x % 2) == 0)
				{
					x = x / 2;
				}
				res.Add(2);
			}

			for (int i = 3; i <= Math.Sqrt(x); i = i + 2)
			{
				if ((x % i) == 0)
				{
					while ((x % i) == 0)
					{
						x = (x / i);
					}
					res.Add(i);
				}
			}

			if (x > 2)
			{
				res.Add(x);
			}
			return res;
		}

		/// 
		/// Function to calculate sum of digits of distinct
		/// prime factors of given number n and sum of
		/// digits of number n and compare the sums obtained
		/// 
		/// 
		/// 
		public static bool IsHoax(int x)
		{
			List pf = PrimeFactors(x);

			if (pf[0] == x)
			{
				return false;
			}

			int all_pf_sum = 0;
			for (int i = 0; i < pf.Count; i++)
			{
				int pf_sum = 0;
				while (pf[i] > 0)
				{
					pf_sum += pf[i] % 10;
					pf[i] /= 10;
				}
				all_pf_sum += pf_sum;
			}

			int sum_n = 0;
			while (x > 0)
			{
				sum_n += x % 10;
				x /= 10;
			}
			return (sum_n == all_pf_sum);
		}
	}
}

 ——————————————————————

POWER BY 315SOFT.COM &
TRUFFER.CN

你可能感兴趣的:(C#算法演义,Algorithm,Recipes,c#,算法,教程)