Welcome, Guest: Register On Nairaland / LOGIN! / Trending / Recent / New
Stats: 3,152,133 members, 7,814,964 topics. Date: Thursday, 02 May 2024 at 02:35 AM

Coding Challenge 3: Sum Of Primes - Programming (2) - Nairaland

Nairaland Forum / Science/Technology / Programming / Coding Challenge 3: Sum Of Primes (3906 Views)

Mini Web Application Coding Challenge For Programmers / Java Coding Challenge: Task Scheduler / Coding Challenge 5: Substring Generator (2) (3) (4)

(1) (2) (Reply) (Go Down)

Re: Coding Challenge 3: Sum Of Primes by Nobody: 10:37pm On Jul 07, 2011
Re: Coding Challenge 3: Sum Of Primes by Mobinga: 7:10am On Jul 08, 2011
Yes! 32 minutes.
Re: Coding Challenge 3: Sum Of Primes by Nobody: 7:19am On Jul 08, 2011
Re: Coding Challenge 3: Sum Of Primes by Ghenghis(m): 11:37am On Jul 08, 2011
32 minutes seems too long for the problem,

When you post benchmark results like time, it would also be nice if you posted the system specs like CPU speed, processor type , RAM, OS etc.
Re: Coding Challenge 3: Sum Of Primes by Ghenghis(m): 12:53pm On Jul 08, 2011

Re: Coding Challenge 3: Sum Of Primes by Mobinga: 12:58pm On Jul 08, 2011
^^ Depends on your code.

Your WEI is 4.2? haha. Mine is 7.3
Re: Coding Challenge 3: Sum Of Primes by Nobody: 3:46pm On Jul 08, 2011
Re: Coding Challenge 3: Sum Of Primes by Fayimora(m): 3:56pm On Jul 08, 2011
hahahaha thats brute force, So what else do you expect? OK run this code below and see the difference

import java.math.*; 

public class SumOfPrimes2
{

public static void main(String[] args)
{
BigInteger sum = BigInteger.ZERO;
for (BigInteger num = BigInteger.ZERO; num.compareTo(BigInteger.valueOf(2000000)) < 0; num = num.nextProbablePrime())
sum = sum.add(num);
System.out.println(sum.toString());
}
}



Re: Coding Challenge 3: Sum Of Primes by Nobody: 4:53pm On Jul 08, 2011
Re: Coding Challenge 3: Sum Of Primes by Fayimora(m): 4:55pm On Jul 08, 2011
ARRRRGGGG!!!!!!! Why are you on this earth, hahhaa Ok you gat me there, hehehehe but yeah thats the fastest way i could think of sad
Re: Coding Challenge 3: Sum Of Primes by Ghenghis(m): 12:58pm On Jul 09, 2011
public class Primer {

    static private  int MAX = 2000000;
    private int[] store = new int[ MAX / 2 ] ;
   
    public static void main(String[] arg){
        Primer p  = new Primer();
        p.checkPrimes();
    }
   
   
    void checkPrimes(){
        int primesFound = 0 ;
        long sumOfPrimes = 0;
        for(int i = 2; i < MAX ; i++){
            if(isPrime(i))
            {
                store[primesFound++] = i;
                sumOfPrimes+=i;
                System.out.println(i+ ","wink;
            }
        }
        System.out.println("total =" + sumOfPrimes);
    }
   
    boolean isPrime(int num){
        int cnt = 0 ;
        Double d = Math.sqrt(num);
        int lim = d.intValue() + 1;
        while(store[cnt] > 0 && store[cnt] < lim){
            if((num % store[cnt]) == 0){
                //not prime
                return false;
            }
            cnt++;
        }
        return true;
    }
   
}
Re: Coding Challenge 3: Sum Of Primes by Fayimora(m): 1:03pm On Jul 09, 2011
wats your runtime nd result?
Re: Coding Challenge 3: Sum Of Primes by Ghenghis(m): 1:32pm On Jul 09, 2011
Fayimora:

wats your runtime nd result?
Ghenghis:



Re: Coding Challenge 3: Sum Of Primes by Fayimora(m): 1:51pm On Jul 09, 2011
hmm ours doesnt look any different from my initial brute force solution,so why is mine takin that much time?
Re: Coding Challenge 3: Sum Of Primes by Ghenghis(m): 2:06pm On Jul 09, 2011
It doesn't look different but ,they are very different. Your solution might take n2 iterations, which is 2,000,0002.


I'll tell u something about primes, they are the building block of every other number. Hence i only need to verify if a number is prime by testing it against other primes. So once u find a prime number store it, you then use it to test other numbers.
Re: Coding Challenge 3: Sum Of Primes by Fayimora(m): 2:08pm On Jul 09, 2011
Oh yah good point, Thanks
Re: Coding Challenge 3: Sum Of Primes by Nobody: 6:03pm On Jul 09, 2011

Re: Coding Challenge 3: Sum Of Primes by Fayimora(m): 6:20pm On Jul 09, 2011
Hmm thats not what i get on my system tho, his code runs for 2.67 secs
Re: Coding Challenge 3: Sum Of Primes by Nobody: 6:30pm On Jul 09, 2011
Re: Coding Challenge 3: Sum Of Primes by Fayimora(m): 6:39pm On Jul 09, 2011
Yope, for some reason, the terminal gives a different time from what other apps give, hmmmm

All ma systems are 64bits.
Re: Coding Challenge 3: Sum Of Primes by skydancer: 12:12am On Jul 12, 2011
Oh geez, that was quite some fun with csharp there. I know c++ is roughly 2times faster  tongue

Here's my code: (took roughly 4 mins on my pc)


using System;
using System.Collections.Generic;

namespace Primes
{
    class Program
    {
        static void Main()
        {
            double total = 0;
            Console.Write("Enter max for check: "wink;
            double max = Convert.ToDouble(Console.ReadLine());
            for (double d = 2; d < max; d ++)
            {
               if(isPrime(d)) total += d;
            }
            Console.WriteLine("The total sum of prime numbers from 1 to {0} is : {1}", max, total + 1);
            Console.ReadLine();
        }

        private static readonly List<double> primes = new List<double>();

        static bool isPrime(double i)
        {
            foreach(double d in primes)
            {
                if(d <= (i/2))
                {
                    if ((i % d) == 0) return false;
                }
            }
            primes.Add(i);
            return true;
        }
    }
}
Re: Coding Challenge 3: Sum Of Primes by Nobody: 12:53am On Jul 12, 2011
Re: Coding Challenge 3: Sum Of Primes by skydancer: 1:06am On Jul 12, 2011
Finally got a bite of this prime-hunting algorithm: http://mathforum.org/library/drmath/view/55813.html
Ghengis, you could have told us why you did the square-root thing, I didn't understand it until now smiley

There is also more complex stuff/tweaks here,  http://www.troubleshooters.com/codecorn/primenumbers/primenumbers.htm

in C++

Talk about execution times of 0.02sec shocked

edit: funny enough it seemed the sqrt operation takes longer than the divide by 2 operation on my PC. undecided

1 Like

Re: Coding Challenge 3: Sum Of Primes by Fayimora(m): 1:07am On Jul 12, 2011
Hahaha hmmm, I hope one day i would be able to write c# code
Re: Coding Challenge 3: Sum Of Primes by Mobinga: 1:38pm On Aug 12, 2011
currentTimeMillis
public static long currentTimeMillis()
Returns the current time in milliseconds. Note that while the unit of time of the return value is a millisecond, the granularity of the value depends on the underlying operating system and may be larger. For example, many operating systems measure time in units of tens of milliseconds.
See the description of the class Date for a discussion of slight discrepancies that may arise between "computer time" and coordinated universal time (UTC).

Returns:
the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC.

Accurately getting total time of runtime use this

long start = System.currentTimeMillis();

System.out.println("Runtime = " + (double)(System.currentTimeMillis() - start) / 1000);


Kinda like the php unixtimestamp thingy.
Re: Coding Challenge 3: Sum Of Primes by ndugba: 8:44am On Jul 17, 2013
Test Your Skill in using For Loop
Write a program to out put the pattern below

Input:[font=Lucida Sans Unicode][/font]
2

Output:

**********
** * *
* * * *
* ***********
* * * *
* * * *
* * * *
********* *
* * * *
** **
***********

Input:
1

output:

**********
* *
* *
* *
* *
* *
* *
**********



For every integer input , the corresponding output should be drawn using asteriks.. Have fun
[/code]
[/quote][quote]
[code]
Re: Coding Challenge 3: Sum Of Primes by Nobody: 3:54pm On Jul 17, 2013
dell_net: Little cheat.
#include <windows.h>
#include <stdio.h>
#include <math.h>
void main()
{
long sum, two_mil;
two_mil = 10; /*change to 2 mil*/
sum =0;
bool prime;
for (long x =2; x < two_mil; x++)
{
prime = false;
for (long p = 2; p < x; p++)
{
if (fmod((double)x / (double)p,1)==0 && (x !=p))
prime = true;
}
if(prime == false)
sum+=x;
}
printf("%d\n", sum);
system("pause"wink;

}

this is a challenge where C/C++ speed counts.
it's time saving that you are not printing each out
looking at the load of time involved, you can obviously save time by noting that
variable assignment cost time so assigning prime to true can be skipped bu just doing the sum+=x there instead
this will also save the if(prime==false) comparison

variable casting also take time.
I dont have much experience in C/C++ but may try me luck in other languages when am less busy.

(1) (2) (Reply)

Interested In Learning PLC Programming And Industrial Automation???? TRY US / My UI/UX Design Collection / University/Polytechnic Web Portal: What Features Would You Love?

(Go Up)

Sections: politics (1) business autos (1) jobs (1) career education (1) romance computers phones travel sports fashion health
religion celebs tv-movies music-radio literature webmasters programming techmarket

Links: (1) (2) (3) (4) (5) (6) (7) (8) (9) (10)

Nairaland - Copyright © 2005 - 2024 Oluwaseun Osewa. All rights reserved. See How To Advertise. 23
Disclaimer: Every Nairaland member is solely responsible for anything that he/she posts or uploads on Nairaland.