繁体   English   中英

可以被给定数字整除的 n 位数字

[英]Number with n digits divisible by given number

我需要找到任何数字 >0,其中 n 个数字(<=10)可以被一个数字 m(<=10)整除。

这是我试过的:

#include <bits/stdc++.h>
using namespace std;

int main() {
    int n, t, k, r=1;
    cin>>n>>t;
    k=n;
    while(k--)
        r*=10;  // i am making 10^n
    r/=10;      // a 0 was in plus

现在我从 10^n 到 10^n + 10 搜索一个可以被 t 整除的数字,知道我有 t<=10,我应该有一个可以被它整除的数字。

    for(int i=r; i<=r+10; ++i)
    if(i%t==0){
            cout<<i;
            return 0;
    }
}

我只有这个例子:

3 2

答案是 712 但我可以输出任何。

对于输入,我的代码是错误的,我不知道为什么。

如果您需要知道多少 N 位数字可以被 M 整除,那么这可以使用公式很容易地完成。 假设我们想知道可以被 17 整除的所有 5 位数字。我们要做的是找到可以被 17 整除的最小的 5 位数字。所以如果我们这样做

10000 % 17

我们得到4所以当我们这样做时

10000 - 4 + 17 

我们得到 10013,它是可以被 17 整除的前 5 位数字。现在我们需要知道 [10013, 99999] 范围内有多少个 17 的倍数。 我们需要找到最大的 5 位整数,我们可以通过简单的整数除法和乘法得到它

99999 / 17 * 17 = 99994

并获得我们采取的倍数

(max   - min  ) / 17
(99994 - 10013) / 17
    89981       / 17 = 5293

更新这是你需要的吗?

第一个数字n,是位数。 第二个数字m,是分频器。

#include <iostream>
#include <string>

using namespace std;
int m, n;
bool searchDivisibleNumbers(int n, int m);

int main()
{
    cin >> n >> m;

    while (searchDivisibleNumbers(n,m))

    return 0;
}

bool searchDivisibleNumbers(int n, int m)
{
    int digits = pow(10, n-1); //huge number of n digits

    while (digits != 0){

        if (digits % m == 0){
            cout << digits << " is divisible by " << m << endl;
        }
        digits--;
    }
    return true;
}

输入:n=3(3 位数) m=17 输出:

    3 17
85 is divisible by 17
68 is divisible by 17
51 is divisible by 17
34 is divisible by 17
17 is divisible by 17
Press any key to continue . . .

这里有一个程序给你:

int main(void)
{
  int i = 0;
  cout << "Enter number: ";
  cin >> i;
  int m = 0;
  cout << "Enter divisor: ";
  cin >> m;
  if (m == 0)
  {
    cerr << "Can't divide by zero, aborting.\n";
    return EXIT_FAILURE;
  }
  cout << "Your number "
       << i;
  if ((i % m) == 0)
  {
    cout << " is divisible by " 
         << m
         << "\n";
  }
  else
  {
    cout << "not divisible by " << m << "\n";
  }
  return EXIT_SUCCESS;
}

您应该能够输入一个 10 位数字和一个除数 m,然后查看结果。

这个问题有两种可能。 1. 如果 M(<10) 则答案将是“MMMMMM....”类型,最多 N 位。 2. 如果 M(==10) 那么如果 N==1 那么就没有可能的数字,因为没有一位数字可以被 10 整除,但是对于 N>1,答案将是“11111..”类型直到 N-1数字后跟“0”。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM