nolw38 nolw38 - 11 days ago 5
C++ Question

c++ - Euler Project - Level 03

I'm going through the level 03' euler project.
Here is my code and I still dont understand why it doesnt work.
Is it a mathematics Problem?
There is a compilation but the result is false. There are all of a number's factors, and not only the primes..
Could someone have a look on it?
Thanks
BR

#include <iostream>
#include <string>
#include <vector>
#include <cmath>
#include <cstdint>
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void facteursden(std::vector<uint64_t>& facteursden, uint64_t number)
{

uint64_t i = 2;

for (i = 1; i <= number; ++i) {
if (number % i == 0) {
facteursden.push_back(i);
}
}
}
//////////////////////////////////////////////
uint64_t factprem(uint64_t n)
{
uint64_t i = 1;

for (i = 1; i*i < n; ++i) {
if (n % i != 0)
return 1; }
return 0;
}

///////////////////////////////////////////////////////////////////////////
int main()
{

std::vector<uint64_t> monTableau1;
facteursden(monTableau1, 49);
uint64_t i = 0;
for (i = 0; i < (uint64_t)monTableau1.size(); ++i) {
if (factprem(monTableau1[i]) == 1) {
std::cout << monTableau1[i] << std::endl; }}

return 0 ;
}

Answer

There are two mistakes in

uint64_t factprem(uint64_t n)

1. In for loop start from

i=2

instead of i=1

2.Function should look like this

uint64_t factprem(uint64_t n)
{
uint64_t i = 1;

for (i = 2; i*i <=n; ++i) {
   if (n % i == 0)
 return 0; }
return 1;
}
Comments