0

I want to use a for loop for all the values of p in the array returned by the function prime (with parameter n). Below is how to do it in Python, but I can't figure how to do it in Solidity...

for p in prime(n):
    // rest of code

Here's the solidity code:

function factorization(uint256 compositeNumber, uint256 limit) constant returns(uint256 pp){
    uint256 g = compositeNumber;
    uint256 x1 = 16;
    uint256 y1 = 5;
    uint256 z1 = 1;
    while (g == compositeNumber){
        g = greatestCommonDivisor(4 * a**3 + 27 * b**2, compositeNumber);
    }
    if (g > 1){
        return g;
    }
    for(uint256 i = 1; i <= limit; i++){ //Might be a problem
        if (i in prime(limit)){          //Problem is here
        pp = i;
        while (pp < limit){
            (x1, y1, z1) = _ecMul(i, x1, y1, z1);
            if (z1 > 1){
                return greatestCommonDivisor(z1, compositeNumber);
            }
            pp = i * pp;
        }
        }
    }
}

function prime(uint256 limit) constant returns(uint256[] memory primes){
    primes = new uint256[](limit +1);
    for (uint256 i = 2; i < limit; i++){
        primes[i] = i;
    } 
    i = 2;
    while(i**2 <= limit){
        if (primes[i] != 0){
            for (uint256 j = 2; j < limit; j++){
                if (primes[i] * j > limit){
                    break;
                }
                else {
                    primes[primes[i] * j] = 0;
                }
            }
        }
        i++;
    }
    for (i = 2; i <= limit; i++){
        if (primes[i] != 0){
            primes[i];
        }
    }
}

Thank you!

1

In solidity there is no such operator as in. You would have to write a function that iterates through the array to check if the element is in the array. This, however, could be quite costly. So another way could be to write a function that checks if a certain number is a prime number. See here or here for information and algorithms.

Just a side comment: It seems like you are calculating the same arrays with prime numbers over and over again by calling prime(limit)from within the loop for(uint256 i = 1; i <= limit; i++. Therefore, apart from replacing the in operator, consider changing your code to

var primenumbers = prime(limit);
for(uint256 i = 1; i <= limit; i++){ //Might be a problem
    if (i in primenumbers){          //Problem is here
        pp = i;
        while (pp < limit){
            (x1, y1, z1) = _ecMul(i, x1, y1, z1);
            if (z1 > 1){
                return greatestCommonDivisor(z1, compositeNumber);
            }
            pp = i * pp;
        }
    }
}

to increase efficiency and decrease the amount of gas (and therefore Ether) spend.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.