C language - and demand factors

And demand factors

Subject description:

Factors and do not include all of its own and a number of factors, such as Factor 12 are so 1,2,3,4,6 factor 12 and 16. Now given a number n (n <= 10 ^ 9), and find its factor.

Input formats:

A number.

Output formats:

A number.

Sample input:

12

Sample output:

16

prompt:

60% of the data, n-<10,000 =;
80% of the data, n-<= 1, 000,000;
100% data, n <= 1,000,000,000;

 

This problem first written when most people think of direct enumeration, enumeration that is, from 1 up to the maximum number of direct factor in addition to itself. So with this piece of code below:

#include <stdio.h>

int main()
{
	long n, s = 0, x;
        int i;
	scanf("%ld", &n);
	for (i = 1; i < n; i++)	{
		if (n % i == 0)
			s += i;
	}
	printf("%ld", s);
	return 0;
}

 

But this code is encountered in large numbers on a timeout. The reason is that from 1 up to too many to enumerate the maximum number of factors, efficiency is too low. There is a solution, that is, when the number of enumeration a factor, flew input is divided by the factor, so that you can only enumerate to the square root of n. code show as below:

#include <stdio.h>
#include <math.h>

int main()
{
	long n, s = 0;
        int i;
	scanf("%ld", &n);
	for (i = 1; i <= sqrt(n); i++)	{
		if (n % i == 0)
			if (i == n / i)
				s += i;
			else
				s = s + i + n / i;
	}
	printf("%ld", s - n);
	return 0;
}

 

Guess you like

Origin www.cnblogs.com/kgdy-wwy-mfkd/p/11072372.html