【数据结构与算法】学习笔记-《算法笔记》-15【简单数学问题】

示例:数字黑洞
在这里插入图片描述

#include <cstdio>
 #include <time.h>
 #include<stdlib.h>
#include<math.h>
#include <vector>
//#include <cstring>
#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

bool cmp(char a, char b)
{
	return a > b;
}

int main()
{
	int num[4];
	int n;

	int max, min;
	while (scanf("%d",&n)!=EOF)
	{
		int output = -1;
		while (output != 6174 && output != 0)
		{
			for (int i = 0; i < 4; i++)
			{
				num[i] = n % 10;
				n /= 10;
			}
			sort(num, num + 4);
			max = num[3] * 1000 + num[2] * 100 + num[1] * 10 + num[0];
			min = num[0] * 1000 + num[1] * 100 + num[2] * 10 + num[3];
			output = max - min;
			if (output == 0)
			{
				printf("%d-%d=0000\n", max, min);
			}
			else
			{
				printf("%d-%d=%d\n", max, min, output);
			}
			n = output;
		}
	}
}

这里输出写的不够好,可以直接写成printf("%04d",n);

守形数

题目描述
守形数是这样一种整数,它的平方的低位部分等于它本身。
比如25的平方是625,低位部分是25,因此25是一个守形数。
编一个程序,判断N是否为守形数。
输入
输入包括1个整数N,2<=N<100。
输出
可能有多组测试数据,对于每组数据,
输出"Yes!”表示N是守形数。
输出"No!”表示N不是守形数。
样例输入
6
11
样例输出
Yes!
No!

#include <cstdio>
 #include <time.h>
 #include<stdlib.h>
#include<math.h>
#include <vector>
//#include <cstring>
#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

bool cmp(char a, char b)
{
	return a > b;
}

int main()
{
	int n, s;
	int num[3];
	while (scanf("%d", &n) != EOF)
	{
		int i = 0;
		s = n * n;
		int len = 0;
		while(n)
		{
			num[i++] = n % 10;
			n /= 10;
			len++;
		}
		bool flag = true;
		for (int i = 0;i<len; i++)
		{
			if (num[i] != s % 10)
			{
				flag = false;
				break;
			}
			s /= 10;
		}
		if (flag == true)
			printf("Yes!\n");
		else
			printf("No!\n");
	}
	return 0;
}

反序数

题目描述
设N是一个四位数,它的9倍恰好是其反序数(例如:1234的反序数是4321)
求N的值
输入
程序无任何输入数据。
输出
输出题目要求的四位数,如果结果有多组,则每组结果之间以回车隔开。

#include "stdafx.h"
#include <cstdio>

using namespace std;

int main()
{
	for (int i = 1000; i <= 2499; i++)
	{
		int a[4] = { 0 };
		int s = 0, temp = i;
		int k = 0;
		while (temp)
		{
			a[k++] = temp % 10;
			temp /= 10;
		}
		s = a[3] + 10 * a[2] + 100 * a[1] + 1000 * a[0];
		if (i * 9 == s)	printf("%d\n", i);
	}
	return 0;
}

迭代求立方根

题目描述
立方根的逼近迭代方程是 y(n+1) = y(n)2/3 + x/(3y(n)*y(n)),其中y0=x.求给定的x经过n次迭代后立方根的值。
输入
输入有多组数据。
每组一行,输入x n。
输出
迭代n次后的立方根,double精度,保留小数点后面六位。
样例输入
4654684 1
65461 23
样例输出
3103122.666667
40.302088

#include "stdafx.h"
#include <cstdio>
 #include <time.h>
 #include<stdlib.h>
#include<math.h>
#include <vector>
//#include <cstring>
#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

int main()
{
	int n;
	double x, y;
	while (scanf("%lf%d", &x, &n)!=EOF)
	{
		y = x;
		for (int i = 0; i < n; i++)
		{
			y = y * 2 / 3 + x / (3 * y*y);
		}
		printf("%lf\n", y);
	}
	return 0;
}
发布了43 篇原创文章 · 获赞 4 · 访问量 1208

猜你喜欢

转载自blog.csdn.net/weixin_42176221/article/details/101861897
今日推荐