Programming Algorithm-minimum number of code divisible by 1 to n (c)

Source: Internet
Author: User
Code that can be divisible by 1 to n at least (c)


Address: http://blog.csdn.net/caroline_wendy


The minimum integer that can be divisible by 1 to n isProduct of all prime numbers from 1 to n.

Evaluate all prime numbers from 1 to n. The prime number factor with the maximum number can only beSQRT (N)To reduce the traversal range.

The time complexity is O (n). O (SQRT (n) * SQRT (n )).


Code:

/* * main.cpp * *  Created on: 2014.7.20 *      Author: Spike *//*eclipse cdt, gcc 4.8.1*/#include <stdio.h>#include <memory.h>#include <math.h>#include <iostream>#include <vector>using namespace std;void Primes (int n, vector<int>& vi) {if (n <= 2)return;bool* a = new bool[n+1];for (int i=1; i<=n; i++)a[i] = true;for (int i=2; i<sqrt(n); i++) {for (int j=2; j*i<=n; j++) {a[i*j] = false;}}for (int i=1; i<=n; ++i)if (a[i])vi.push_back(i);delete[] a;}int main(void){vector<int> vi;int n = 3;Primes(n, vi);long long min = 1;for (size_t i=0; i<vi.size(); ++i) {min *= vi[i];}cout << "min = " << min << endl;return 0;}


Output:

min = 30030




Programming Algorithm-minimum number of code divisible by 1 to n (c)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.