Converting C++ for loop to python

This is the place for queries that don't fit in any of the other categories.

Converting C++ for loop to python

Postby sc25893 » Mon May 27, 2013 10:28 am

Hi everyone,

I am beginning python and trying to convert one of my simple C++ programs to see the differences in the languages. I am a bit stuck on the following function which is part of my original program:

C++

Code: Select all
bool sumOfPrimeFactorsIsPrime(int number) //works out if a number is prime or not, returns true or false accordingly
{
    //divide each test number from isPrime(i) by up-to-or-equal the square root to find prime
    for (int i = 2; i <= sqrt(number); i++)
    {
        if (number % i == 0)
        {
            return false;
        }
    }
    return true;
}


Python

Code: Select all
def sum_of_prime_factors_is_prime(number):
    for i in range(2, math.sqrt(number)):
        if (number % i == 0):
            return False
    return True


I'm not 100% the above python is correct. My biggest concern is translating the i <= sqrt(number). My range in the python script here does not do that by the looks of it.

Code: Select all
for (int i = 0; i < 5; i++)


would become

Code: Select all
for i in range(0,5)


but what would:

Code: Select all
for (int i = 0; i <= 5; i++)


become?

Thanks.

*EDIT*

If it helps, this is the program so far:

Code: Select all
import math

def get_sum_of_prime_factors(number):
    x = 2
    sum_of_prime_factors = 0
   
    while True:
        if (number % x == 0):
            number = number / x
            sum_of_prime_factors += x
        else:
            x += 1
        if (x <= number):
            break
   
def sum_of_prime_factors_is_prime(number):
    for i in range(2, math.sqrt(number)):
        if (number % i == 0):
            return False
    return True

for i in range(1, 1001):
    if (sum_of_prime_factors_is_prime(get_sum_of_prime_factors(i))):
        print "{} has prime factors that add together to equal a prime number".format(i)
        print "The sum of prime factors are {}".format(get_sum_of_prime_factors(i))


Right now, nothing happens when I run it. No errors, no output. Trying to see where I've gone wrong without too much success. Any hints as to solving this are greatly appreciated.
sc25893
 
Posts: 23
Joined: Sat May 18, 2013 2:51 pm

Re: Converting C++ for loop to python

Postby Mekire » Mon May 27, 2013 11:54 am

Seems you are on the right track. Firstly you will need to int the sqrt in your range as range requires integers. Then you will find our primality checker will return false positives for certain conditions. One being the number 1 (program will crash with negatives). The other being the case of the number only having one factor which happens to be its square root. You need to go one passed the square root in your range call as the end point is non-inclusive.

I believe the following is correct:
Code: Select all
import math

def is_prime(number):
    if number < 2:
        return False
    for i in range(2,int(math.sqrt(number)+1)):
        if not number%i:
            return False
    return True

-Mek
User avatar
Mekire
 
Posts: 1031
Joined: Thu Feb 07, 2013 11:33 pm
Location: Amakusa, Japan

Re: Converting C++ for loop to python

Postby sc25893 » Mon May 27, 2013 12:18 pm

Hi Mek,

Still having no luck with this despite your help, thanks.

This is the full, original C++ code that I wrote:

Code: Select all
/*
 Design a program that finds all numbers from 1 to 1000 whose prime factors, when added
 together, sum up to a prime number (for example, 12 has prime factors of 2, 2, and 3, which sum to 7, which is prime). Implement the code for that algorithm.
 */

#include <iostream>
#include <cmath>

int getSumOfPrimeFactors(int number);
bool sumOfPrimeFactorsIsPrime(int number);

int main()
{
    for (int i = 1; i <= 1000; i++)
    {
        if (sumOfPrimeFactorsIsPrime(getSumOfPrimeFactors(i)))
        /*
         BREAKS DOWN LIKE THIS (FOR MY SELF REFERENCE!):
         if (sumOfPrimeFactorsIsPrime(getSumOfPrimeFactors(i))) - i is substituted with loop variable, 1 through 1000
         --- if (sumOfPrimeFactorsIsPrime(getSumOfPrimeFactors(12))) - sum of prime factors for 12 are 2 x 2 x 3, so added, 2 + 2 + 3 = 7
         ------ if (sumOfPrimeFactorsIsPrime(7)) - function works out whether 7 is a prime number or not, returns true or false
         --------- if (true)
         ------------print number
         */
        {
            std::cout << i << " has prime factors that add together to equal a prime number!" << std::endl;
            std::cout << "The sum of the prime factors are: " << getSumOfPrimeFactors(i) << std::endl << std::endl;
        }
    }
}


int getSumOfPrimeFactors(int number) //gets the prime factors of the number (using variable x)
{
    int x = 2;
    int sumOfPrimeFactors = 0;
   
    while (x <= number)
    {
        if (number % x == 0)
        {
            number = number / x;
            sumOfPrimeFactors = sumOfPrimeFactors + x; //adds together the prime factors of the number
        }
        else
        {
            x++;
        }
    }
   
    return sumOfPrimeFactors; //returns the value of the prime factors added together to be used in function sumOfPrimeFactorsIsPrime(int number)
}

bool sumOfPrimeFactorsIsPrime(int number) //works out if a number is prime or not, returns true or false accordingly
{
    //divide each test number from isPrime(i) by up-to-or-equal the square root to find prime
    for ( int i = 2; i <= sqrt(number); i++)
    {
        if (number % i == 0)
        {
            return false;
        }
    }
    return true;
}


Outputs like this when I run the above in xcode:

Code: Select all
1 has prime factors that add together to equal a prime number!
The sum of the prime factors are: 0

2 has prime factors that add together to equal a prime number!
The sum of the prime factors are: 2

3 has prime factors that add together to equal a prime number!
The sum of the prime factors are: 3

5 has prime factors that add together to equal a prime number!
The sum of the prime factors are: 5

6 has prime factors that add together to equal a prime number!
The sum of the prime factors are: 5

7 has prime factors that add together to equal a prime number!
The sum of the prime factors are: 7

.....etc etc etc.....


I am going over my python code again and again, plus looking at your snippet. Made some changes, but still can't seem to find the source of the zero output.

*EDIT* Ok, I made some changes to my program to find out why I get no ouput. Seems I am stuck in an infinite loop:

Code: Select all
import math

def get_sum_of_prime_factors(number):
    x = 2
    sum_of_prime_factors = 0
   
    while True:
        if (number % x == 0):
            number = number / x
            sum_of_prime_factors += x
            print "HELLO"
        else:
            x += 1
            print "GOODBYE" #I am stuck in this loop here
        if (x <= number):
            break
   
def sum_of_prime_factors_is_prime(number):
    for i in range(2, int(math.sqrt(number)+1)):
        if (number % i == 0):
            return False
    return True

for i in range(1, 50):
    if (sum_of_prime_factors_is_prime(get_sum_of_prime_factors(i))):
        print "{} has prime factors that add together to equal a prime number".format(i)
        print "The sum of prime factors are {}".format(get_sum_of_prime_factors(i))
    else:
        print "Hello program, can you hear me?!?!" #this should run AT LEAST, however, this line never runs!



Output:

Code: Select all
GOODBYE
GOODBYE
GOODBYE
GOODBYE
GOODBYE
GOODBYE
...and on and on and on...
sc25893
 
Posts: 23
Joined: Sat May 18, 2013 2:51 pm

Re: Converting C++ for loop to python

Postby sc25893 » Mon May 27, 2013 12:45 pm

I believe I've got it:

Code: Select all
import math

def get_sum_of_prime_factors(number):
    x = 2
    sum_of_prime_factors = 0
   
    while x <= number:
        if (number % x == 0):
            number = number / x
            sum_of_prime_factors += x
        else:
            x += 1     
    return sum_of_prime_factors
   
def sum_of_prime_factors_is_prime(number):
    for i in range(2, int(math.sqrt(number)+1)):
        if (number % i == 0):
            return False
    return True

for i in range(2, 50):
    if (sum_of_prime_factors_is_prime(get_sum_of_prime_factors(i))):
        print "{} has prime factors that add together to equal a prime number".format(i)
        print "The sum of prime factors are {}".format(get_sum_of_prime_factors(i))


Output appears the same as the c++ version. I changed range to start from 2 as there's no need to start from 1. Thanks for the input :)
sc25893
 
Posts: 23
Joined: Sat May 18, 2013 2:51 pm


Return to General Coding Help

Who is online

Users browsing this forum: No registered users and 2 guests