题目描述
小明对某些数字有偏爱,例如,他喜欢7的倍数,而不喜欢4的倍数,如果一个整数是7的倍数,而不是4的倍数,小明会认为这个数字是他的幸运数字。现在给定两个整数m和n,请你帮小明找m到n范围内的最大的幸运数字。如果m到n范围内没有幸运数字,则输出“no”
输入
两个正整数m和n(m < =n,且均小于10的9次方)
输出
一个整数,即m到n范围内的最大的幸运数字。
样例输入 Copy
90 100
样例输出 Copy
98
解题方法
方法一:从前往后
unsigned Max = 0; //根据题意可以将最大值初始化为0
for (unsigned i = m; i <= n; i++)
if (i % 7 == 0 && i % 4 != 0)
Max = i;
if (Max > 0)
cout << Max;
else
cout << "no";
方法二:从后往前
unsigned i;
for (i = n; i >= m; i--)
if (i % 7 == 0 && i % 4 != 0)
{
cout << i;
break;
}
if (i < m)
cout << "no";
程序代码如下(使用C++)
#include<iostream>
using namespace std;
int main()
{
unsigned m, n, i; //m<=n,且均小于10的9次方
cin >> m >> n;
/*
unsigned Max = 0; //根据题意可以将最大值初始化为0
for (unsigned i = m; i <= n; i++)
if (i % 7 == 0 && i % 4 != 0)
Max = i;
if (Max > 0)
cout << Max;
else
cout << "no";
*/
for (i = n; i >= m; i--)
if (i % 7 == 0 && i % 4 != 0)
{
cout << i;
break;
}
if (i < m)
cout << "no";
return 0;
}