我试图通过在Project Eular页面上执行示例来学习更多有关C代码的知识:http://projecteuler.net/problems 目前我试图从数字600851475143算出最高素数因子。 这是我的代码:
/* The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?*/
#include <stdio.h>
unsigned long long GetPrimeFactor(unsigned long long number)
{
/* printf("The number you typed was %d\n", number);*/
unsigned long long prime = 2;
unsigned long long LargestPrime = 0;
while (prime != 0)
{
if(number%prime == 0)
{
if(number == prime)
{
if(LargestPrime < prime)
LargestPrime = prime;
printf("End of prime factors \nLargest Prime: %d\nEnding Number: %d\n", LargestPrime, number);
break;
}
else if(LargestPrime < prime)
LargestPrime = prime;
//divide number by prime
number = number/prime;
printf("Prime: %d\n", prime);
}
else
{
//get new prime
prime = nextPrimeNumber(prime);
}
}
}
unsigned long long nextPrimeNumber(unsigned long long input)
{
unsigned long long nextPrimeNumber;
while(input !=0)
{
if( input < 0)
{
printf("The number you have entered is negative\n");
}
else if (input > 0)
{
nextPrimeNumber = input + 1;
if(nextPrimeNumber%2 == 0 && nextPrimeNumber != 2)
{
nextPrimeNumber += 1;
}
while(!isPrime(nextPrimeNumber))
{
nextPrimeNumber += 2;
}
return nextPrimeNumber;
}
}
}
int isPrime(int number)
{
int i;
int prime = 1; //true
if(number == 2)
prime = 0; //false
if(number%2 == 0 || number <= 1)
prime = 0;
else
{
for(i=3; i<sqrt(number) && prime == 1; i+=2)
if(number%i == 0)
prime = 0;
}
return prime;
}
int main(void)
{
unsigned long long number;
printf("Enter a Number: \n");
scanf("%d", &number);
GetPrimeFactor(number);
return 0;
}
此代码适用于示例中的数字13195,但是当我尝试更大的数字并且我不确定什么是错误时会变坏。
大数字输出600851475143:素数:3素数:29素数:5108231等 这是不正确的,因为无论如何这个数字都不能被3整除。
不能解决什么问题,所以任何帮助都会很棒
答案 0 :(得分:2)
签名ints
上升到2147483647,unsigned ints
上升到4294967295,您可以使用unsigned long long
上升到18446744073709551615,如果您需要更大的东西,请使用任意精度/ bignum图书馆,如GnuMP(http://gmplib.org/)
更新已编辑的问题:
你使用的scanf的格式说明符甚至不读取整个unsigned long long
,我读到你必须使用%llu
的地方,但是在我的gcc上这不起作用,我必须使用:
printf("Enter a Number: \n");
scanf("%I64d", &number);
printf("%I64d", number); // <- make sure that this prints the number you
// gave it before even calling GetPrimeFactor()
答案 1 :(得分:0)
scanf("%L", &number)