0
when I put a small number in my algorithm it works, but if the number is large the program returns 0, I tried to put unsigned int, long, etc and it didn’t work... Here’s the code:
#include <stdio.h>
#include <stdlib.h>
/*
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
*/
int primo(int num);//declarando a função
int menorDiv();
const long numz = 600851475143;
int main(){
//1 - pegar os divisores do numero
//2 - verificar se esse divisor é primo
//3 - pegar o maior divisor primo do numero 600851475143
int i, maior = 0, primao;
for ( i = 1; i <= menorDiv(); i++){
if( i % 2 == 0)
continue;
if ( primo(i) == 0){//se for primo
if ( numz % i == 0){
primao = i;
}
}
}
printf("%d", primao);
return 0;
}
int menorDiv(){//pega o menor divisor do numero grandao
int i, menor;
for ( i = 1; i < numz; i++){
if( numz % i == 0){
menor = (float)numz/i;
break;
}
}
return menor;
}
int primo(int num){
int i, contador = 0;
for ( i = 1; i <= num; i++){
if( num % i == 0){
contador++;
}
}
if ( contador == 2){
return 0;
}
return 1;
}
I made some edits in the code and the final version was like this:
#include <stdio.h>
#include <stdlib.h>
/*
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
*/
const long long num = 600851475143;
long long menorDiv(long long num);
long long primo(long long i);
int main(){
// 1 - pegar os divisores primos
// 2 - pegar o maior
long long i, primu;//declara i como long long
for ( i = 0; i < menorDiv(num); i++){
if ( primo(i) == 0){//caso seja primo faça
if( num % i == 0){
primu = i;
}
}
}
printf("%ld", primu);
return 0;
}
long long menorDiv(long long num){//pega o menor numero que seja divisivel pelo numero para que o programa nao continue rodando apos esse numero
long long i, result;
for ( i = 1; i <= num; i++){
if( num % i == 0){
result = num/i;
break;
}
}
return result;
}
long long primo(long long i){
int contador = 0;
long long j;
for ( j = 1; j < i; j++){
if( i % j == 0){
contador++;
}
}
if( contador == 2){
return 0;
}
return 1;
}
But still unsuccessful, the code keeps running and not stopping... it seems to have gone into infinite looping, but I can’t find anywhere that this might have happened
when I put 13195 on numz the result of 29 that is correct, but when putting 600851475143 returns 0, it should return 6857
– Ruan