Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
855 views
in Technique[技术] by (71.8m points)

c - Counting Positive Integers with a Given Number of Divisors

basically what i was trying to do is insert an integer k that represents the number of divisors and then finding all the numbers that have k divisors from 1-100000

#include <stdio.h>

int main(void)
{
    int k, x = 1, y = 100000, divisor, count;

    printf("Enter the target number of divisors:
");
    scanf("%d", &k);



    for (divisor = 0; divisor <= 1; divisor++)
        if (x % divisor == 0 && y % divisor == 0)
           count++;

    printf("There are %d numbers between 1 and 100000 inclusive which have exactly %d   divisors
", k, divisor);

    return 0;
}

However I can't seem to be able to do it, please do help me as I'm fairly new to the programming scene and haven't found an answer elsewhere.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There is a theorem that states if you have the canonical representation of an integer being a1b1 * a2b2 ... anbn then the number of divisors of this integer is (b1 + 1) * (b2 + 1) ... (bn + 1).

Now that you have this theorem, you can modify slightly Eratosthenes's sieve to get all integers up to 100 000 in canonical form.

Here is some code that does what I mean by modified erathosthenes's sieve.

const int size = 100000;
int devs[size + 1];
void compute_devs() {
  for (int i = 0; i < size + 1; ++i) {
    devs[i] = (i%2 == 0) ? 2 : 1;
  }

  int o = sqrt(size);    
  for (int i = 3; i <= size; i += 2) {
    if (devs[i] != 1) {
      continue;
    }
    devs[i] = i;
    if (i <= o) {
      for (int j = i * i; j < size; j += 2 * i) {
        devs[j] = i;
      }
    }
  }
}

After calling compute_devs the value of devs will store the value of the greatest prime divisor of each number up to size. I will leave the rest of the task to you, but having this array it becomes pretty straight forward.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...